Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!