Mongoose: fully qualified query name with regex
I am using the following code to find a user by name or by name:
var re = new RegExp(req.params.search, 'i');
User.find()
.or([{ firstName: re }, { lastName: re }])
.exec(function(err, users) {
res.json(JSON.stringify(users));
});
Works search
well if equal to 'John'
or 'Smith'
, but not for 'John Sm'
.
Any clue how to accomplish this request?
Thank!
Disclaimer . This question originally popped up in the comments of this previous question 3 years ago and remains unanswered. I am starting a new thread because 1) It was not the main question and 2) I find it interesting enough to have its own thread
EDIT:
Suppose the database contains two records: John Smith
and John Kennedy
.
- Query
John
should return bothJohn Smith
andJohn Kennedy
- The request
John Sm
should only returnJohn Smith
source to share
Separate the search query with words and separate them with the alternation operator ('|').
var terms = req.params.search.split(' ');
var regexString = "";
for (var i = 0; i < terms.length; i++)
{
regexString += terms[i];
if (i < terms.length - 1) regexString += '|';
}
var re = new RegExp(regexString, 'ig');
For input, 'John Smith'
this will create a regex that looks like /John|Smith/ig
. This will return true for individual words and will also work when the input is'John Sm'
You can play around with this regex to get another one that suits your needs.
EDIT:
The problem is your name fields are separate. In this case, applying the same regex to both fields will not produce the results you want. The regex must be applied to the same fully qualified field.
A possible solution is using aggregation:
User.aggregate()
.project({fullName: {$concat: ['$firstName', ' ', '$lastName']}})
.match({fullName: re})
source to share