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

255
Views
MongoDB findOne using $and & $elemMatch not working?

I am trying to check if there is an existing conversation between two users before creating another one.

My Conversation object stores the conversation participants in an array, I need to return a conversation object that has BOTH participants (senderId & recId) that exists in my database but I am unable to build to correct MongoDB query to get it.

Please see the queries I have tried below because I have tried all manner of using $and & $elemMatch but can't get it to work.

Thank you

Conversation Model

const conversationSchema = mongoose.Schema(
  {
    participants: [participantSchema],
  },
   {timestamps: true}
)

const participantSchema = mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      required: true, 
      ref: `User`,
    },
    username: {
      type: String,
      required: true,
    }
  }
)

Conversation Object

{
  _id: 61cb6316asas4b54e09168234,
  participants: [
    {
      userId: 61b777ea6815a69a625b,
      username: 'johnsmith'
    },
    {
      userId: 61bc0dcbe7181ccfd806,
      username: 'testuser'
    }
  ],
  createdAt: 2021-12-28T19:18:46.673Z,
  updatedAt: 2021-12-28T23:41:12.364Z
}

Queries I have tried that ARE NOT what I need or don't work

   // null - no convo found when the convo definitely exists in db 
  const existingConvo = await Conversation.findOne({
      $and: [{ userId: senderId }, { userId: recId }],
    })

    // works but only checks for ONE id property
    // if I make an array: "Query filter must be an object, got an array"  
    const existingConvo = await Conversation.findOne({
      participants: { $elemMatch: { userId: senderId } },
    })

    // "Unknown operator $and"
    const existingConvo = await Conversation.find({
      participants: {
        $and: [{ userId: senderId }],
      },
    })

   // returns empty array when it should have the convo object
    const existingConvo = await Conversation.find({
      participants: { $all: [{ userId: senderId }, { userId: recId }] },
    })

about 4 years ago · Juan Pablo Isaza
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!