嗨,我正在使用猫鼬来搜索我的收藏中的人物.
/*Person model*/
{
name: {
first: String,
last: String
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想搜索有查询的人:
let regex = new RegExp(QUERY,'i');
Person.find({
$or: [
{'name.first': regex},
{'name.last': regex}
]
}).exec(function(err,persons){
console.log(persons);
});
Run Code Online (Sandbox Code Playgroud)
如果我搜索约翰,我会得到结果(如果我搜索Jo,则为事件).但如果我搜索John Doe,我显然没有得到任何结果.
如果我将QUERY更改为John | Doe,我会得到结果,但它会返回所有在姓氏或名字中都有John或Doe的人.
接下来就是尝试使用mongoose textsearch:
首先将字段添加到索引:
PersonSchema.index({
name: {
first: 'text',
last: 'text'
}
},{
name: 'Personsearch index',
weights: {
name: {
first : 10,
last: 10
}
}
});
Run Code Online (Sandbox Code Playgroud)
然后修改Person查询:
Person.find({
$text …
Run Code Online (Sandbox Code Playgroud)