小编Car*_*ten的帖子

用部分字符串进行Mongoose文本搜索

嗨,我正在使用猫鼬来搜索我的收藏中的人物.

/*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,我会得到结果,但它会返回所有在姓氏或名字中都有JohnDoe的人.

接下来就是尝试使用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)

text-search mongoose mongodb node.js

13
推荐指数
2
解决办法
1万
查看次数

标签 统计

mongodb ×1

mongoose ×1

node.js ×1

text-search ×1