Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda