【问题标题】:Full-Text Search in Node JS with Mongoose使用 Mongoose 在 Node JS 中进行全文搜索
【发布时间】:2017-04-09 23:10:50
【问题描述】:

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

【问题讨论】:

  • 你用的是哪个版本的 mogoose?
  • 目前使用 Mongoose 4.7.0
  • 你需要在你的字段上创建一个文本索引:example

标签: javascript node.js mongodb mongoose full-text-search


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您需要为您的架构添加一个文本索引,如下所示:

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

    如果您想包含所有字符串字段

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

    【讨论】:

      【解决方案3】:

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

      $正则表达式

      为模式匹配字符串提供正则表达式功能 在查询中。
      MongoDB 使用 Perl 兼容的正则表达式(即 “PCRE”) 8.42 版,支持 UTF-8。

      要使用 $regex,请使用以下之一 以下语法:

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

      在 MongoDB 中,您还可以使用正则表达式对象(即 /pattern/) 来指定正则表达式:

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

      【讨论】:

        猜你喜欢
        • 2013-04-06
        • 1970-01-01
        • 2019-06-14
        • 2020-01-12
        • 2022-10-17
        • 2020-05-06
        • 2019-11-25
        • 2012-07-29
        • 2023-03-02
        相关资源
        最近更新 更多