Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose find() document with two fields with one search parameter

My node model contains following properties

firstName
lastName
age
address

I need to use mongoose find functions to filter user with firstName and lastName.

My UI pass only one search parameter. Data should filter as follows

'fistName' like 'search parameter' & lastName like 'search Parameter'.

I pass following object to find function.It did not work for me.

var criteria = {
    'firstName' : req.body.customerName ? { $regex: req.body.customerName, $options: 'i' } : null ,
    'lastName' : req.body.customerName ? { $regex: req.body.customerName, $options: 'i' } : null 
};
like image 666
Janith Widarshana Avatar asked Dec 02 '22 13:12

Janith Widarshana


2 Answers

If you want to get data if match with both fields of firstName and lastName then you can use $and operator with $regex.

var query = {$and:[{firstName:{$regex: req.body.customerName, $options: 'i'}},{lastName:{$regex: req.body.customerName, $options: 'i'}}]}

and If you want to get data if match with any one field of firstName and lastName then you can use $or operator with $regex.

var query = {$or:[{firstName:{$regex: req.body.customerName, $options: 'i'}},{lastName:{$regex: req.body.customerName, $options: 'i'}}]}

so can try this code:

var query = {}
if(req.body.customerName) {
  query = {$or:[{firstName:{$regex: req.body.customerName, $options: 'i'}},{lastName:{$regex: req.body.customerName, $options: 'i'}}]}
}

ModelName.find(query , function (err, data) {
   if(error) {
     // return error
   }
   //return data
});
like image 178
Shaishab Roy Avatar answered Dec 27 '22 01:12

Shaishab Roy


So, I think you have a logical flaw in addition to a syntactic flaw. Unless you're intentionally looking only for people who have the same first name and last name (e.g. Tom Tom), then you'll never find anyone by simply finding on both fields with the same value in each. If, as I suspect, you really want to take a search criteria and see if a user has that string in either their first name or last name, then you'll actually want to use $or.

Something like:

let query = {};
if(req.body.customerName){
   const nameExp = new RegExp('^'+req.body.customerName+'$', 'i');
   query = { $or : [ { firstName: nameExp }, { lastName: nameExp } ] }; 
}

MyModel.find(query, (err, data) => { /* do your thing */ });
like image 43
Paul Avatar answered Dec 27 '22 01:12

Paul