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

Full-Text Search in Node JS with Mongoose

我正在尝试对 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);
                }
        });

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

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

如果要包含所有字符串字段

,请使用userSchema.index({'$**': 'text'});

要使 $text 查询正常工作,MongoDB 需要使用文本索引对字段进行索引。要通过 mongoose 创建此索引,请使用

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

See here 用于 MongoDB 文本索引文档。

如果出于某种原因无法添加测试索引,您还可以在聚合管道中使用 regex 运算符来匹配字符串。

$regex

Provides regular expression capabilities for pattern matching strings in queries.
MongoDB uses Perl compatible regular expressions (i.e. “PCRE” ) version 8.42 with UTF-8 support.

To use $regex, use one of the following syntaxes:

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

In MongoDB, you can also use regular expression objects (i.e. /pattern/) to specify regular expressions:

{ <field>: /pattern/<options> }