napster993
napster993

Reputation: 165

Creating query with Mongoose library (find objects in array)

This is my Mongoose model of conversation object:

const conversationSchema = mongoose.Schema({
  participants: [
    {
      id_profile: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }
    }
  ]
});

How I can find a conversation object that contains two objects in the array "participants" that have ID = 123456 and ID = 654321? The order of objects in array "participants" can be different.

conversation = {
  participants: [
    { id_profile: '123456' },
    { id_profile: '654321' }
  ]
}

conversation = {
  participants: [
    { id_profile: '654321' },
    { id_profile: '123456' }
  ]
}

How to create a query using Mongoose?

Upvotes: 1

Views: 59

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can use $all for this query, which finds docs where a field matches all of a set of values:

Conversation.find({'participants.id_profile': {$all: ['123456', '654321']}})

Upvotes: 2

Related Questions