node.js - get array if array contains id mongoose -


it tricky one. thought use $in, after querying, wasn't looking for.

this 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 make following, send user id, if players array contains id, return other id (the array have length 2) in array.

the context can lookup against whom have played before.

this had, "players" should array , it's not games want return,

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

can 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 strings 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 assumption want array of unique player ids not player id passed in. kept vars split apart instead of chaining of array methods, in attempt improve readability.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -