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

120
Views
how apply in mongoDB multiple conditions if key exist
const filterOptions = {
        carColor: req.query.carColor, 
        languages: { $regex: `${req.query.languages}`, $options: 'i' },
        incomeMonth: { $gte: req.query.incomeMonth },
        incomeYear: { $gte: req.query.incomeYear },
        age: { $gte: query.fromAge, $lt: query.toAge }, // age from - to
        familyStatus: query.familyStatus
    }

    const profiles = await Profile.find(filterOptions)
        .sort({ createdAt: 1 })
        .limit(100)

    return res.json({ success: true, count: profiles?.length, profiles })

for example I have multiple query, and one of theme language key: req.query.language, and I wanna apply only for this query key $regex method, otherwise if empty key for any, I don't wanna pass it into find() method

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You should fill the filterOptions object, conditionally, only for keys that exist.

let filterOptions = {};
if (req.query.carColor) {
  filterOptions =  {...filterOptions, carColor: req.query.carColor};
} 
if (req.query.languages) {
  filterOptions =  {...filterOptions, languages: { $regex: `${req.query.languages}`, $options: 'i' }};
}
if (req.query.incomeMonth) {
  filterOptions =  {...filterOptions, incomeMonth: { $gte: req.query.incomeMonth }};
}
if (req.query.incomeYear) {
  filterOptions =  {...filterOptions, incomeYear: { $gte: req.query.incomeYear }};
}
if (req.query.fromAge && req.query.toAge) {
  filterOptions =  {...filterOptions, age: { $gte: query.fromAge, $lt: query.toAge }};
}
if (req.query.filmStatus) {
  filterOptions =  {...filterOptions, familyStatus: query.familyStatus};
}
almost 4 years ago · Santiago Trujillo 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!