嗨,我正在使用猫鼬来搜索我收藏中的人。
/*Person model*/
{
name: {
first: String,
last: String
}
}
现在我想搜索有查询的人:
let regex = new RegExp(QUERY,'i');
Person.find({
$or: [
{'name.first': regex},
{'name.last': regex}
]
}).exec(function(err,persons){
console.log(persons);
});
如果我搜索John我会得到结果(如果我搜索Jo的事件)。但是,如果我搜索John Doe ,我显然不会得到任何结果。
如果我将QUERY更改为John|Doe,我会得到结果,但它会返回所有姓氏/名字中包含John或Doe的人。
接下来是尝试使用猫鼬文本搜索:
首先将字段添加到索引:
PersonSchema.index({
name: {
first: 'text',
last: 'text'
}
},{
name: 'Personsearch index',
weights: {
name: {
first : 10,
last: 10
}
}
});
然后修改 Person 查询:
Person.find({
$text : {
$search : QUERY
}
},
{ score:{$meta:'textScore'} })
.sort({ score : { $meta : 'textScore' } })
.exec(function(err,persons){
console.log(persons);
});
这工作得很好!但现在它只返回与整个名字/姓氏匹配的人:
->约翰返回值
-> Jo没有返回值
有没有办法解决这个问题?
首选没有外部插件的答案,但也希望有其他答案。