Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Mongoose query user ids inside an array property

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!