猫鼬用$ text搜索查询错误的集合

时间:2019-08-11 21:37:41

标签: node.js mongodb express mongoose

我正在尝试使用MongoDB $ text search 查询在我的两个字段上设置的 compound text 索引。

创建索引没有问题,并在 mongo shell 中调用db.card.getIndexes()会返回以下内容:

{
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "adatabase.cards"
        },
        {
                "v" : 2,
                "key" : {
                        "_fts" : "text",
                        "_ftsx" : 1
                },
                "name" : "name_text_description_text",
                "ns" : "adatabase.cards",
                "weights" : {
                        "description" : 3,
                        "name" : 5
                },
                "background" : true,
                "default_language" : "english",
                "language_override" : "language",
                "textIndexVersion" : 3
        }

通过以下快速途径查询卡片集合后:

router.route('/searchcards')
  .post((req, res, next) => {
    let query = req.query.q;
    Card.find({
      $text: { $search: query }
    }, { score: { $meta: "textScore" } }
    ).sort( { score: { $meta: "textScore" } } )
    .then(q => {
      console.log(q); 
      res.send(q)
    })
    .catch(next)
  });

我收到错误:

MongoError: text index required for $text query (no such collection 'adatabase.users')

为什么mongo会尝试查询用户集合?

这是我的猫鼬卡模式。

const CardSchema = new mongoose.Schema({
  name: {type: String, required: true, maxlength: [100, 'Name must be less than 100 characters']},
  user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  days: [{type: mongoose.Schema.Types.ObjectId, ref: 'Day'}],
  locations: [{type: mongoose.Schema.Types.ObjectId, ref: 'Location'}],
  description: {type: String, required: true, maxlength: [500, 'Description must be less than 500 characters']},
  settings: {
      private: {type: Boolean, required: true, default: false}
  },
  meta: {
      created: { type : Date, default: Date.now },
      view_count: {type: Number, default: 0},
      tags: [String],
      likes: {type: Number, default: 0},
      numberOfComments: {type: Number, default: 0},
      numberOfShares: {type: Number, default: 0}
  },
    comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}],
});

CardSchema.options.autoIndex = true;

CardSchema.index({
  name: 'text',
  description: 'text',
}, {
  weights: {
    name: 5,
    description: 3,
  },
})

1 个答案:

答案 0 :(得分:0)

结果证明我是从用户模型路径导入卡模型的。哇!