Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda