mongodbsearchsearchqueryset

How to make a search query in MongoDB


I have profiles in a collection called Profiles. I am making the query to search profiles based on user provided fields. Searching Form(UI Form), User have different options to search profiles like 'female' or 'male' or 'Any' and click on Search button. This way an user can search my collection Profiles by providing the combination of following fields.

So, for example user selects fields as: Gender: 'Female', Country: 'Pakistan', City: 'Islamabad', Marital Status: 'Any', Education: 'Any', Religion: 'Islam' then what will be query for MongoDB?

I need to have a dynamic query for all cases, please.

I tried so far:

Profile.find(
    {
        gender: req.body.gender,
        country: req.body.country,
        city: req.body.city,
        maritalStatus: req.body.maritalStatus,
        education: req.body.education,
        religion: req.body.religion
    },
    {},
    function(err, profiles){
        if(profiles!=null)
            { res.status(200).json({status: true, message:'Profile(s) found', profiles})}
        else
            {res.status(404).json({status: false, message:'No profile(s) found.'})}
    }
);

but above query is not dynamic for all cases.


Solution

  • Just extract the fields that are present in the req.body object and add them in an object. This object will be used to filter query results

    const filter = Object.entries(req.body)
                         .reduce((acc, curr) => (acc[curr[0]] = curr[1], acc), {});
    

    at the end you will have a filter object that will contain only those properties that user chose. You can pass this filter object in your query

    Profile.find(filter, {}, function(err, profiles) {
        if(profiles!=null)
              return res.status(200).json({status: true, message:'Profile(s) found', profiles});
    
        res.status(404).json({status: false, message:'No profile(s) found.'});
    });