Home > OS >  How to find specific item in mongodb database or all items?
How to find specific item in mongodb database or all items?

Time:11-04

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 ?

CodePudding user response:

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 .

CodePudding user response:

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);
}
  • Related