1

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.

  • Gender
  • Country
  • City
  • Marital Status
  • Education
  • Religion

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.

M.Shahid
  • 13
  • 3

1 Answers1

0

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.'});
});
Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • thank you for quick answer this cleared me one thing that is about 'Any' case, by excluding that field from query. But I am sorry this is't not working. – M.Shahid Nov 08 '19 at 15:15
  • what do you mean not working? This way you willl query the database on the basis of the values passed in request body. They could be of the fields of `Profiles` collection or some of them – Yousaf Nov 08 '19 at 16:32
  • Got it thats perfect. And response status needs condition modification like: if(profiles.length>0) as it will return an array of profiles. Thank you. – M.Shahid Nov 09 '19 at 09:12