【问题标题】:Mongoose not creating index猫鼬没有创建索引
【发布时间】:2012-09-29 00:08:07
【问题描述】:

我最近开始使用 Mongoose (v.3.2.1),但我遇到了索引问题。

我在我的架构 ( Schema.path('attr').index(true) ) 上定义了几个索引,并且它们没有在数据库中创建。 (我在 shell 中运行 db.collection.getIndexKeys() 并且只看到 _id 索引)。

请注意,有时会创建部分/全部索引。

我打开了调试,我看到 ensureIndex() 正在运行:

mongoose.set('debug', true);

Mongoose: myColl.ensureIndex({ type: 1 }) { safe: true, background: true }  
Mongoose: myColl.ensureIndex({ created: 1 }) { safe: true, background: true }  
Mongoose: myColl.ensureIndex({ updated: 1 }) { safe: true, background: true }  

我也听过错误:

mongoose.connection.on('error', function(err) {
    console.error('MongoDB error: %s', err);
});

myCollModel.on('index',function(err) {
    console.error('MongoDB error: %s', err);
});

我可以在控制台中看到我的插入和查询,但没有错误。

任何帮助将不胜感激!

谢谢,

尼赞酒吧

我的架构是这样定义的:

myColl = new Schema();

myColl.add({
     text : { type: String, required : true }
   , shortText: { type: String }
   , type : { type: String , index: true}
   , correctAnswerId : { type: ObjectId, ref: QuestionAnswer}
   , answers: { type: [ QuestionAnswer ] }
});

在这种情况下,不创建“类型”索引。请注意,有时在运行 ensureIndexes() 几次后,它们会被创建。

谢谢!

【问题讨论】:

  • 很奇怪。您可以发布定义您的 myCollModel 架构的代码吗?

标签: node.js indexing mongoose


【解决方案1】:

当定义一个 ObjectId 引用另一个集合中的文档的字段时,ref 属性的值是模型的字符串名称,而不是模型本身。所以它应该看起来像这样:

correctAnswerId : { type: ObjectId, ref: 'QuestionAnswer' }

我感觉失败的时间正在影响是否创建 type 索引。

【讨论】:

  • 谢谢,我试过了,但还是有同样的问题。我什至完全删除了该字段,但仍然没有创建索引。
【解决方案2】:

确实,我也遇到了同样的问题。

然后我把 ensureindex 调试信息复制到 mongo 终端试一下,命令已发送(就像从 mongoose 控制台显示的那样),但是由于 mongo 的问题,创建失败:

{
    "err" : "ns name too long, max size is 128",
    "code" : 10080,
    "n" : 0,
    "connectionId" : 78,
    "ok" : 1
}

然后我给出选项 {name: 'super_index'},然后就完成了。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 2021-04-01
    • 2018-08-19
    • 2020-04-27
    • 2021-10-13
    • 2021-12-31
    • 2017-09-04
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多