【问题标题】:MongoDB index search works in console, but not from browserMongoDB 索引搜索在控制台中工作,但不能在浏览器中工作
【发布时间】:2017-11-26 07:01:26
【问题描述】:

昨天所有这些都正常工作,所以我真的不确定出了什么问题。我已经在 SO 上进行了搜索,并多次阅读了文档和步骤,但我还没有让它工作。一如既往地感谢任何帮助!

如果我在 shell 中键入db.movies.find({ '$text': { '$search': 'elephant' } }),它会返回一个标题列表,其中包含标题中的“大象”。但是,如果我从浏览器运行相同的搜索,它会使节点服务器崩溃,我得到MongoError: text index required for $text query

错误来自find()的错误响应:

Movie.find(
  { '$text': { '$search': 'elephants' } },
  (err, movies) => {
    if (err) throw err; // MongoError: text index required for $text query
    if (!movies) {
      res.json({
        data: null,
        success: false,
        message: 'No movies data'
      });
    } else {
      res.json({
        success: true,
        data: movies
      });
    }
  })

我的数据库中的索引如下所示:

{
        "v" : 2,
        "key" : {
            "_fts" : "text",
            "_ftsx" : 1
        },
        "name" : "title_text",
        "ns" : "db.movies",
        "weights" : {
            "title" : 1
        },
        "default_language" : "english",
        "language_override" : "language",
        "textIndexVersion" : 3
    }

我还定义了猫鼬模式,并且我正在使用自动增量插件在每个电影保存时增加自定义 id 字段。 (保存电影有效,所以我连接到数据库好了)

  mongoose.model('Job', new Schema({
    id: Number,
    title: String,
    desc: String,
    genre: String
  })
  .index({ title: 'text' })
  .plugin(autoIncrement.mongoosePlugin));

【问题讨论】:

  • 第二组参数{ score... }是干什么用的?
  • find() 有一个使用$meta: 'textScore'.sort(),它也必须在查找中定义为一个arg。我将更新问题以包含该完整对象而不是变量
  • 你是否在 shell 中运行过完全相同的查询(带排序)?
  • 您声明可以在shell 中运行查询,但没有提及您传递给Movie.find 的第二个参数对象。这会给你带来麻烦吗?

标签: javascript node.js mongodb indexing mongoose


【解决方案1】:

正如@Chris Satchell 在 cmets 中指出的那样 将索引添加到猫鼬模式可以解决这个问题。

代替:

mongoose.model('Job', new Schema({
    id: Number,
    title: String,
    desc: String,
    genre: String
  })

这样做:

mongoose.model('Job', new Schema({
    id: Number,
    title: { type: String, text: true },
    desc: String,
    genre: String
  })

即使我在 Schema 上仍然有 .index({ title: 'text' }),您仍然需要在属性上定义 { type: String, text: true }

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多