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

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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