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

Jas*_*ch1 7 javascript full-text-search mongoose mongodb 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 }
Run Code Online (Sandbox Code Playgroud)

但是,我确实在用户架构的字段上声明了文本索引,并且我确认已创建文本索引,因为我使用的是mLab.我正在尝试对字段执行全文搜索

这是我的用户架构:

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

这是我的全文搜索代码:

User.find({$text: {$search: search}}, function (err, results) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(results);
                }
        });
Run Code Online (Sandbox Code Playgroud)

hzi*_*oun 8

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

userSchema.index({fields: 'text'});
Run Code Online (Sandbox Code Playgroud)

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


Dev*_*Dig 8

要使$text查询起作用,mongodb需要使用文本索引为该字段编制索引.通过mongoose使用创建此索引

fields: {type: [String], text: true}
Run Code Online (Sandbox Code Playgroud)

请参阅此处获取文本索引的mongodb文档.