mongodb - How to write a Mongoose query for items whose IDs are not in an array -


i have 2 models: event , people.

schemas.event = new mongoose.schema({     eventid: number,     name: {type: string},     size: number,     location: {type: string},     date: {type: date},          people: [{type: mongoose.schema.types.objectid, ref: models.person}],     note: {type: string} }); 

and people

schemas.person = new mongoose.schema({     firstname: {type: string},     lastname: {type: string},     age: number,     email: {type: string},     gender: {type: string} }); 

given event, want query using mongoose, find people not registered event.

something like

models.person.find({not in event.people}); 

the tricky thing me is, event.people not array of ids, rather array of objects like

[         {             "$oid": "558ced061d35bd072e7b5825"         },         {             "$oid": "558ced061d35bd072e7b58a0"         },         {             "$oid": "558ced061d35bd072e7b58c6"         }     ], 

is there way make query?

firstly, need create array of objectid's using native javascript method map() creates new array results of calling provided function on every element in array:

var mongoose = require("mongoose"); var arr = event.people.map(function(item){ return mongoose.types.objectid(item["$oid"])}); 

you can query collection using $nin operator expression:

models.person.find({"_id": { "$nin": arr}}).exec(callback); 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -