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

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

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

最佳答案

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

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

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

关于javascript - 使用 Mongoose 在 Node JS 中进行全文搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40806871/

相关文章:

mongodb - 在 MongoDB shell 查询中获取 "data from collection b not in collection a"

javascript - 格式化 AJax 调用返回的 Json 并将其分配给 javascript 变量

javascript - 使用 JS 在 2 个图像之间交替而不是使用 GIF

javascript - 如何在 Node.js 中进行 Craigslist 电子邮件转发(接收电子邮件到自动生成的电子邮件地址并转发)?

mongodb - 如何在 MongoDB 中启用数据压缩

java.lang.IllegalStateException : open 错误

javascript - 如何设置 ember 引擎?

javascript - 如何测试使用来自已分派(dispatch)操作的数据的 Saga

javascript - 在 Node.js (v10.9.0) 中对元素进行排序会返回错误结果

node.js - NestJS .env 文件未构建