代码之家  ›  专栏  ›  技术社区  ›  João Otero

猫鼬:确保索引在insertmany之后运行

  •  0
  • João Otero  · 技术社区  · 6 年前

    我在模式中设置了两个复合索引

    (...)
    ModelSchema.index({"field1":1, "field2":1, "field3": 1, "field4": 1})
    ModelSchema.index({"field1":1, "field2":1, "field3": -1, "field4": -1}) 
    module.exports = mongoose.model('Model', ModelSchema)
    

    那我打电话来

    Model.insertMany(itemsArray)
    

    在mongo shell中,我可以看到两个索引都是创建的。然而,当我试图查询带有第二个索引提示的集合时,我得到了一个错误。

    所以我做的就是打开Mongoose调试

    mongoose.set('debug', true)
    

    在日志中,我可以看到操作的顺序如下:

    Mongoose: models.ensureIndex({"field1":1, "field2":1, "field3": 1, "field4": 1})
    Mongoose: models.insertMany([....])
    (...other operations of my code happening here)
    Mongoose: models.ensureIndex({"field1":1, "field2":1, "field3": -1, "field4": -1}) 
    Mongoose: models.indexInformation({ full: true })
    

    所以,在我看来,这两件事正在发生:

    • 在确保第二个索引之前插入
    • 索引在我的代码已经执行时异步发生。

    在将项插入集合之前,如何保证两个索引都得到保证?

    0 回复  |  直到 6 年前