使用 Mongoose 在 Node JS 中进行全文搜索

新手上路,请多包涵

我正在尝试对 Mongoose 中的字符串数组执行全文搜索,但出现此错误:

 { [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);
                }
        });

原文由 Jasch1 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 470
2 个回答

对于 $text 查询工作,MongoDB 需要使用文本索引对该字段进行索引。通过猫鼬使用创建此索引

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

有关文本索引的 MongoDB 文档, 请参见此处

原文由 DevDig 发布,翻译遵循 CC BY-SA 4.0 许可协议

您需要向架构中添加文本索引,如下所示:

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

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

原文由 hzitoun 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题