0

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 
      })

1
  • 1
    Try to use $all to replace $elemMatch and see if it can solve your issues. Commented Dec 25, 2021 at 15:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.