2016-11-25 95 views
1

我想在猫鼬字符串数组上进行全文搜索,我得到这个错误:全文搜索与猫鼬

{ [MongoError: text index required for $text query] 
    name: 'MongoError', 
    message: 'text index required for $text query', 
    waitedMS: 0, 
    ok: 0, 
    errmsg: 'text index required for $text query', 
    code: 27 } 

不过,我有一个文本索引宣布对用户架构的领域,我证实了,因为我使用MLAB文本索引已创建。 我想执行的领域

这里全文搜索我的用户模式:

var userSchema = mongoose.Schema({ 
     local: { 
      firstName: String, 
      lastName: String, 
      username: String, 
      password: String, 
      fields: {type: [String], index: true} 
     } 
}); 

这里是我的全文搜索代码:

User.find({$text: {$search: search}}, function (err, results) { 
       if (err) { 
        console.log(err); 
       } else { 
        console.log(results); 
       } 
     }); 
+0

您正在使用哪个版本mogoose? – Mitchapp

+0

目前使用的猫鼬4.7.0 – Jasch1

+0

你需要在你的领域创建文本索引:[示例](https://docs.mongodb.com/manual/reference/operator/query/text/#examples) –

回答

6

对于$text查询工作,MongoDB的需要索引字段的文本索引。要创建这个索引由猫鼬使用

fields: {type: [String], text: true} 

See here文本索引的MongoDB的documenation。

2

您需要到文本索引添加到您的架构如下图所示:

userSchema.index({fields: 'text'}); 

或者使用userSchema.index({'$**': 'text'});如果要包括所有字符串字段