Mongoose: find document by values inside an array field

Viewed 942

I've got a chat schema that looks like that:

var chatSchema = new mongoose.Schema({
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        required: true
    }]
});

It contains array of user IDs. Now I want to find one chat document that contains an array of two user IDs.

At the beginning I tried to do this:

Chat.findOne({ users: { $in: [req.user_id, receiver._id] }})
    .then(chat => { })

But it seems that every time it gives me the chat that contains at least one of the IDs I mentioned in the query.

So I've tried to change it to this but with no luck:

Chat.findOne()
    .where({ users: { $in: [req.user_id] }})
    .where({ users: { $in: [receiver._id] }})
    .then(chat => { })

I need to find the chat that contains both of the user ID's inside the users array otherwise I expect for a null value.

How can I achieve this goal?

Thanks!

1 Answers

This is the way $in works - returns the document when at least one value matches. You should use $all instead:

Chat.findOne({ users: { $all: [req.user_id, receiver._id] }})
Related