1

It is a tricky one. I thought I could use $in, but after querying, it wasn't where I was looking for.

This is my schema

var gameSchema = new mongoose.Schema({
    state: {
        type: String,
        default: "invited"
    },
    finished: {
        type: Boolean,
        default: false
    },
    players: {
        type: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'users'
        }],
        required: true,
    },
    scores: [scoreSchema],
    chat : [chatSchema]
});

The request I'm trying to make is the following, I send a user Id, if the players array contains this Id, return the other id (the array will always have length 2) in the array.

The context is that you can lookup against whom you have played before.

This is what I had, but "players" should be an array and it's not games that I want to return, so

exports.getFriends = function(id, cb){
    gameSchema.find({ id: { "$in": "players"} }, function(err, games){
        if(err){
            return cb(err, null);
        }
        else{
            return cb(null, games);
        }
    });
};

1 Answer 1

1

Can you try this?

exports.getFriends = function(id, cb){
    gameSchema.find({ players: id }, function(err, games) {
        if (err) {
            return cb(err);
        }
        const players = games.map(game => game.players);
        const mergedPlayers = [].concat.apply([], players);
        const mappedPlayers = mergedPlayers.map(String); // convert ObjectIds to strings for comparisons.
        const idString = String(id);
        const filteredPlayers = mappedPlayers.filter(player => player !== idString);
        const uniquePlayers = filteredPlayers.filter((player, index, arr) => arr.indexOf(player) === index);
        return cb(null, uniquePlayers);
    });
};

I'm operating under the assumption that you want an array of the unique player ids that are not the player id you passed in. I kept the vars split apart instead of chaining all of the array methods, in an attempt to improve readability.

Sign up to request clarification or add additional context in comments.

7 Comments

this should work. I believe you can query for specific values in array properties the same way you query for a String, etc.
Yup. It's a bit odd, in my opinion. My first instinct was to try to use a $contains operator, but I don't think that exists in mongo.
It is but I love how easy it is to query for things in MongoDB. :)
but how do I fetch the other id from the array? or even just the array players, so I can letter extract distinct id's
What do you want the output to be? An array of every player in each of those games which is not the id you passed in?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.