how apply in mongoDB multiple conditions if key exist

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

0 Answers
Related