阅读了一些在 Mongoose 中使用“LIKE”的解决方案后:
Mongoose.js: Find user by username LIKE value
How to query MongoDB with "like"?
我使用此代码在 Mongoose 中模拟“SQL LIKE”:
查找:'joseph' --> 结果: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);
}
});
其结果是用户 Josephine Doyle,OK。
现在我想使用相同的代码,但用这个词来搜索:
查找:'josephine do' --> 结果:Josephine Doyle
var word = 'josephine do';
好的,也可以...
示例多于作品:
查找:'josephine doyle' --> 结果:Josephine Doyle
查找:'jos doyle' --> 结果:Josephine Doyle
但是,我想解决这个问题:
- 查找:'doyle josephine' --> 结果:{}
- 查找:'do josephine' --> 结果:{}
查找:'doyle jo' --> 结果:{}
(不同的订单词不起作用)
查找:“约瑟芬”
doyle' --> 结果:{}
(单词之间不能有多个空格)
有什么建议吗?也许另一个正则表达式?谢谢!
最佳答案
您可以通过分割字符串并使用 $and
搜索每个单词来完成此操作。 .
类似于:
var name = 'doyle josephine';
var toSearch = name.split(" ").map(function(n) {
return {
name: new RegExp(n.trim(), 'i')
};
});
User
.find({ $and: toSearch })
关于javascript - Mongoose MongoDB : LIKE operator in search,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29648626/