1

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?

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

mongoose.Types.ObjectId(item["$oid"]) seems to be returning a brand new oid which is not what I want. I think I will just return item["$oid"] ... edit: but it returns null....
What about if you map it directly without casting to ObjectId event.people.map(function(item){ return item["$oid"]});?
Yes, it worked now. I made a mistake in that I was populating them before... anyway it works now! Thanks a lot
0

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/

1 Comment

Just as an FYI: your answer is more of a comment than an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.