Home > Mobile >  Mongoose query user ids inside an array property
Mongoose query user ids inside an array property

Time:12-26

I have a messaging app where a conversation model stores the participants of a unique conversation.

I am trying to query for a specific conversation where two userIds are inside the participant array but I get the error message 'Query filter must be an object, got an array '.

I tried putting the array inside an object but it didn't work and not sure how to make this query work OR if there is a better way to perform this search.

What am I doing wrong?

MODEL

const conversationSchema = mongoose.Schema(
  {
    participants: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: `User`
      }
    ]
  }
)

EXPRESS ROUTE CODE


  const existingConvo = await Conversation.findOne({
        participants: { $elemMatch: [msg.senderId, msg.recId] },
        // ^ Query filter must be an object, got an array 
      })

CodePudding user response:

Your use case should require a $all instead of $elemMatch since you require the participants array to contain both/all users in your query array.

Your code should be like this:

const existingConvo = await Conversation.findOne({
    participants: { $all: [msg.senderId, msg.recId] }
})

Here is the Mongo playground for you to reference the behaviour of $all in native mongo query.

  • Related