Reputation: 5889
After read some solutions to use "LIKE" in Mongoose:
Mongoose.js: Find user by username LIKE value
How to query MongoDB with "like"?
I'm using this code to simulate "SQL LIKE" in Mongoose:
Find: 'joseph' --> Result: Josephine Doyle
var word = 'joseph';
User
.find({name: new RegExp(word, 'i')})
.sort('-created')
.exec(function(err, users){
if (err) {
console.log(err);
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(users);
}
});
The result of this is the user Josephine Doyle, OK.
Now I want to use the same code, but with this word to search:
Find: 'josephine do' --> Result: Josephine Doyle
var word = 'josephine do';
OK, works too...
More examples than works:
Find: 'josephine doyle' --> Result: Josephine Doyle
Find: 'jos doyle' --> Result: Josephine Doyle
But, I want to solve this case of problems:
Find: 'doyle jo' --> Result: {}
(Different order words doesn't work)
Find: 'josephine
doyle' --> Result: {}
(With more than one space between words doesn't work)
Any suggestions? Maybe another RegEx? Thanks!
Upvotes: 2
Views: 871
Reputation: 32118
You can do this by splitting the string and searching each word using $and
.
Something like:
var name = 'doyle josephine';
var toSearch = name.split(" ").map(function(n) {
return {
name: new RegExp(n.trim(), 'i')
};
});
User
.find({ $and: toSearch })
Upvotes: 3