2

Having some issues performing a findOne query with an array of ObjectIds. Simplified schema as follows:

Model:

var InboxSchema = new Schema({
    _users: [
        {
            type: mongoose.Schema.ObjectId,
            ref: 'User',
            required: 'Users are required',
            unique: true
        }
    ]
}

mongoose.model('Inbox', InboxSchema)

Query:

var users = [];
var userIds = ['5567ead844997f969fe3f00f', '558b8492f1723b090b414765'];

for (var i=0; i<userIds.length; i++) {
    users.push(new mongoose.Types.ObjectId(userIds[i]));
}

Inbox.findOne({_users: users}).exec(function (err, inbox) {
    console.log(inbox);
}

Inbox always returns null despite it returning something when using Mongo shell, so I know that my query works. Previously, I was querying on just userIds alone, which I later realised was not working as I would have to query using ObjectId. However, even converting the strings to ObjectId doesn't work.

1 Answer 1

5

Try using the mongo array query operators $all or $in.

$all to match a target to all of the array elements:

Inbox.findOne({ "_users": { "$all": users} }).exec(function (err, inbox) {
    console.log(inbox);
})

$in to match a target to any of the array elements:

Inbox.findOne({ "users": { "$in": users} }).exec(function (err, inbox) {
    console.log(inbox);
})
Sign up to request clarification or add additional context in comments.

6 Comments

It's also worth noting that the OP doesn't need to manually cast the strings to ObjectIds as Mongoose will do that for you based on the schema.
I wish all :"first posts" were of such quality. Many people can learn from the succint and true points made here. My edits are only to add links that maybe you cannot, and improve the portabilty of JSON syntax. Well done.
Solved the issue. Thanks @AdamWysocki for the help.
@JohnnyHK: I was wondering about the casting, thanks for the tip.
@AdamWysocki Not that chatter is a good thing here either, but see what I just did there with @ and your username. That is how you "tag" here to alert and respond to those who comment. Unless they are watching people don't see your comments otherwise. Best look at the "help center" link. Happy contributing.
|

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.