Reputation: 23302
I have two models: Event
and 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 a certain event, I want to do a Query using Mongoose, to find all the people not already registered for this event.
Something like
models.Person.find({not in event.people});
The tricky thing for me is, that event.people
is not an array of IDs, but rather it is an array of Objects that look like
[
{
"$oid": "558ced061d35bd072e7b5825"
},
{
"$oid": "558ced061d35bd072e7b58a0"
},
{
"$oid": "558ced061d35bd072e7b58c6"
}
],
Is there any way to simply make this query?
Upvotes: 1
Views: 646
Reputation: 103335
Firstly, you need to create an array of the ObjectId's by using the native JavaScript method map()
which creates a new array with the results of calling a provided function on every element in this array:
var mongoose = require("mongoose");
var arr = event.people.map(function(item){ return mongoose.Types.ObjectId(item["$oid"])});
You can then query the collection using that as the $nin
operator expression:
models.Person.find({"_id": { "$nin": arr}}).exec(callback);
Upvotes: 3
Reputation: 6676
Look into the following operators:
$not - http://docs.mongodb.org/manual/reference/operator/query/not/
$in - http://docs.mongodb.org/manual/reference/operator/query/in/
$nin - http://docs.mongodb.org/manual/reference/operator/query/nin/
Upvotes: 0