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

241
Vistas
How to dynamically nest $or operator into $and Mongoose statement?

Suppose I have 3 MongDB entries in a movie database:

"books": [
  {
    "_id": "xxxxxx",
    "title": "Fast Five",
    "rating": 6
  },
  {
    "_id": "yyyyyy",
    "title": "Kill Bill",
    "rating": 8
  },
  {
    "_id": "zzzzzzzz",
    "title": "Jumanji",
    "rating": 5
  }
]

I use GraphQL to retrieve the id of multiple movies if their title and rating match the criteria:

query{
   getMovies(itemFilterInput: {titles:["Fast Five", "Jumanji"], rating:6}){
    _id
   title
  }
}

This should return Fast Five. I want this to translate into a mongoDB query like this:

{$and: [{rating:6}, {$or: [{title:"Fast Five", title:"Jumanji"}]}]}

In the backend, I use NodeJS and Mongoose to handle this query and I use something like this:

 getMovies: async args => {
try{
  let d = args.itemFilterInput;
  let filters = new Array();

  const keys = Object.keys(d);
  keys.forEach((key) => {
      // The titles case
      if(d[key] instanceof Array){
        var sObj = {};
        var sObjArray = [];
        d[key].map(prop => {
          sObj[key] = prop;
          sObjArray.push(sObj);
        });
        filters.push({$or: sObjArray});
      }else{
        // The rating case
        var obj = {};
        obj[key] = d[key];
        filters.push(obj);
      }
  });

  const items = await Item.find({$and: filters});
  return items.map(item => {
    return item;
  });
} catch (err) {
  throw err;
}

}

Unfortunately, this approach does not work. What is the correct way to nest $or parameters in $and params?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Answer:

First of all, it is better to use the $in operator instead of a $and/$or combination.

And to solve the error: use quotes everywhere to declare the query.

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