Mongoose无法创建索引。

4

我最近开始使用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);
});

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

任何帮助将不胜感激!

谢谢,

Nitzan Bar

我的模式定义如下:

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 ] }
});

在这种情况下,'type'索引并未被创建。请注意,有时在运行ensureIndexes()几次后它们才会被创建。
谢谢!

奇怪。您能发布定义myCollModel模式的代码吗? - JohnnyHK
2个回答

0
定义一个字段时,如果它是对另一个集合中的文档的ObjectId引用,则ref属性的值应该是模型的字符串名称,而不是模型本身。因此,它应该像这样:
correctAnswerId : { type: ObjectId, ref: 'QuestionAnswer' }

我有一种感觉,那个失败的时间会影响是否创建了type索引。


1
谢谢,我尝试了但仍然遇到同样的问题。我甚至完全删除了该字段,但索引仍未创建。 - Nitzo

0

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

然后我将 ensureindex 的调试信息复制到 mongo 终端中尝试执行该命令(就像 mongoose 控制台中显示的一样),但由于 mongo 的问题,创建失败了:

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

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

希望对你有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接