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

134
Visualizações
How to find specific item in mongodb database or all items?

I'm trying to find a specific item like this :

Product.find({ category: "bracelet" });

But in one case I need to put either a value like bracelet in category or basically say category of any like this :

  let cat;
  if (req.body.cat) {
    cat = req.body.cat;
  } else {
    cat = "";
  }

  let products;
  try {
    products = await Product.find({ category: cat });
  } catch (e) {
    return next(e);
  }

So I put an empty string to find all items no matter what category field value they have but it doesn't work and returns an empty array .

How can I achieve this kind of behavior which says if there is a cat field on the request body search for that otherwise search for all items no matter of what category field value they have ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

let cat;
if (req.body.cat) {
 cat = req.body.cat;
} else {
  cat = {$regex:".*."};
}

let products;
try {
 products = await Product.find({ category: cat });
} catch (e) {
 return next(e);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I solved the issue with a trick by saying find all that have category field or category field exist :

  let cat;
  if (req.body.cat) {
    cat = req.body.cat;
  } else {
    cat = { $exists: true };
  }

This way It will either search for the category from the request body if included and if not it will get all the items with category field .

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