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
};
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
});
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 */ });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With