Mongoose文档
当您的应用程序启动时,Mongoose会自动调用为架构中每个定义的索引创建索引。Mongoose会呼叫依次为每个索引创建索引,并在当所有createIndex调用成功时,或者当错误。虽然对开发来说很好,但建议使用这种行为在生产中被禁用,因为创建索引可能会导致性能影响。通过设置autoIndex禁用行为将您的模式选项设置为false,或通过将选项autoIndex设置为false。
文档似乎没有说明当我们设置autoIndex: false
时会发生什么。索引是在后台创建的,还是我必须编写另一个程序或脚本来确保索引在生产中正确完成?
这适用于所有这些场景吗?
- 默认索引,如
_id
createdAt
上的索引类似于someCollection.index({ createdAt: 1 })
- 像
new Schema({ someData: { type: String, default: '', index: true})
一样内联创建的索引
这个线程意味着我们可以使用db.ensureIndex({ name: 1 }, { background: true });
,但当我在猫鼬文档中寻找类似的语法时,我只找到了以下
const userSchema = new Schema({
email: { type: String, required: true, unique: true },
registeredAt: { type: Date, index: true }
});
// [ [ { email: 1 }, { unique: true, background: true } ],
// [ { registeredAt: 1 }, { background: true } ] ]
userSchema.indexes();
注释掉的部分有background: true
,但它与email: { type: String, required: true, unique: true, background: true },
之类的模式定义不一致。我不明白他们想在那里传达什么。
这个帖子说...an index build can happen in the "background"...
,但我没有在猫鼬文档中看到这一点。也许我错过了它,或者问题是当我的应用程序使用mongoose
处理所有mongodb
操作时,不理解何时在mongodb文档中引用mongose文档。
查看此处https://github.com/Automattic/mongoose/issues/5342看起来选项{ background: true }
是Mongoose创建索引时的默认选项,您可以覆盖它。
至于你的问题:
这适用于所有这些场景吗?
- 默认索引,如_id
- 主索引从集合开始就存在
- 对createdAt的索引类似于someCollection.index({createdAt:1}(
- 如果适用,则不会在关闭autoIndex的情况下创建此索引
- 索引像新架构一样以内联方式创建({someData:{type:String,default:",index:true}(
- 如果适用,则不会在关闭autoIndex的情况下创建此索引