Mongoose 不创建索引 [英] Mongoose Not Creating Indexes

查看:35
本文介绍了Mongoose 不创建索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试创建 MongoDB 索引.使用 Mongoose ODM 并在下面的架构定义中,我将用户名字段设置为唯一索引.集合和文档都被正确创建,只是索引不起作用.所有文档都说应该在启动时运行 ensureIndex 命令以创建任何索引,但没有创建任何索引.如果这很重要,我正在使用 MongoLab 进行托管.我也多次放弃收藏.怎么了.

Trying to create MongoDB indexes. Using the Mongoose ODM and in my schema definition below I have the username field set to a unique index. The collection and document all get created properly, it's just the indexes that aren't working. All the documentation says that the ensureIndex command should be run at startup to create any indexes, but none are being made. I'm using MongoLab for hosting if that matters. I have also repeatedly dropped the collection. What is wrong.

var schemaUser = new mongoose.Schema({
    username: {type: String, index: { unique: true }, required: true},
    hash: String,
    created: {type: Date, default: Date.now}
}, { collection:'Users' });

var User = mongoose.model('Users', schemaUser);
var newUser = new Users({username:'wintzer'})
newUser.save(function(err) {
    if (err) console.log(err);
});

推荐答案

在模型上钩住 'index' 事件,查看异步创建索引时是否发生错误:

Hook the 'index' event on the model to see if any errors are occurring when asynchronously creating the index:

User.on('index', function(err) {
    if (err) {
        console.error('User index error: %s', err);
    } else {
        console.info('User indexing complete');
    }
});

此外,通过调用启用 Mongoose 的调试日志记录:

Also, enable Mongoose's debug logging by calling:

mongoose.set('debug', true);

调试日志将向您显示 ensureIndex 调用它为您创建索引.

The debug logging will show you the ensureIndex call it's making for you to create the index.

这篇关于Mongoose 不创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆