猫鼬没有创建索引

时间:2012-09-17 03:35:05

标签: javascript node.js mongodb mongoose

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

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

8 个答案:

答案 0 :(得分:21)

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

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

此外,通过调用:

启用Mongoose的调试日志记录
mongoose.set('debug', true);

调试日志记录将显示正在为您创建索引的ensureIndex调用。

答案 1 :(得分:4)

Mongoose宣布"if the index already exists on the db, it will not be replaced"credit)。

例如,如果您之前已经定义了索引{ "responseHeader":{ "zkConnected":true, "status":0, "QTime":7, "params":{ "q":"*:*", "indent":"on", "wt":"json", "_":"1485246329559"}}, "response":{"numFound":0,"start":0,"maxScore":0.0,"docs":[] }} ,但是您想将其更改为{unique: true},那么遗憾的是,Mongoose根本不会这样做,因为该字段已存在索引DB。

在这种情况下,您可以删除现有索引,然后mongoose将从fresh创建一个新索引:

{unique: true, sparse: true}

请注意,这是heavy operation,因此请谨慎对待生产系统!

在另一种情况下,我的索引没有被创建,因此我使用了JohnnyHK推荐的错误报告技术。当我这样做时,我收到了以下回复:

$ mongo
> use MyDB
> db.myCollection.dropIndexes();
> exit
$ restart node app

这是因为我的新索引添加了约束E11000 duplicate key error collection ,但是集合中的现有文档并不是唯一的,因此Mongo无法创建索引。

在这种情况下,我需要修复或删除包含重复字段的文档,然后再次尝试创建索引。

答案 2 :(得分:1)

当我在无法正常工作的模型上挂接索引事件时,我开始在控制台上收到一条错误消息,指出“字段'retryWrites'对于索引规范无效。”我的应用程序中唯一引用“ retryWrites”的位置是在连接字符串的末尾。我删除了它,重新启动了应用程序,索引重建成功。我将retryWrites放回原处,重新启动了应用程序,错误消失了。我的用户集合(一直给我带来问题)是空的,因此当我使用Postman制作新记录时,我(与Mongo Compass社区)看到了创建的新记录,现在出现了索引。我不知道retryWrites的作用-今天是我使用它的第一天-但这似乎是我问题的根源。

哦,为什么我要用它?它固定在我从Mongo的Atlas Cloud网站提取的连接字符串上。它看起来很重要。嗯。

答案 3 :(得分:1)

可能是解决您的问题

var schema = mongoose.Schema({
speed: Number,
watchDate: Number,
meterReading: Number,
status: Number,
openTrack: Boolean,
 });
schema.index({ openTrack: 1 });

答案 4 :(得分:0)

猫鼬连接选项没有指定:

autoIndex: false

答案 5 :(得分:0)

就我而言,我必须明确指定from copy import copy my_cmap = copy(plt.cm.get_cmap('viridis')) my_cmap.set_under('lightgrey') plt.pcolormesh(all_x_values, all_y_values, data_storage, cmap=my_cmap, vmin=0.000001) plt.colorbar(extend='min', extendrect=True)

autoIndex: true

答案 6 :(得分:0)

我在编写数据导入命令行实用程序时遇到了这个问题。执行结束后,一些索引被创建,一些没有。

解决方案是在终止脚本之前调用 await model.ensureIndexes()。无论 autoIndex 选项值如何,它都有效。

答案 7 :(得分:0)

正如您在 mongoose 文档 https://mongoosejs.com/docs/guide.html#indexes 中看到的,我们需要定义 schema.index 来创建我们的索引。看看下面的代码进行测试:

  • 注意,更新架构后重启服务器进行检查。
const schemaUser = new mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
      index: true,
      unique: true,
      dropDups: true,
    },
    hash: String,
    created: {
      type: Date,
      default: Date.now,
    },
  },
  {
    autoCreate: true, // auto create collection
    autoIndex: true, // auto create indexes
  }
)
// define indexes to be create
schemaUser.index({ username: 1 })

const User = mongoose.model('Users', schemaUser)
const newUser = new Users({ username: 'wintzer' })
newUser.save(function (err) {
  if (err) console.log(err)
})
相关问题