Mongoose docs
When your application starts up, Mongoose automatically calls createIndex for each defined index in your schema. Mongoose will call createIndex for each index sequentially, and emit an 'index' event on the model when all the createIndex calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false, or globally on the connection by setting the option autoIndex to false.
The docs don't seem to address what happens when we set autoIndex: false
. Will indexes be created in the background or do I have to write another program or script to make sure indexes are done properly in production?
Does this apply to all these scenarios the same?
- default index like
_id
- indexes on
createdAt
likesomeCollection.index({ createdAt: 1 })
- indexes created inline like
new Schema({ someData: { type: String, default: '', index: true})
.
This thread implies we can use db.ensureIndex({ name: 1 }, { background: true });
But when I look for similar syntax in the mongoose docs I only found the following
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();
The commented out section has background: true
but it's not inline with the schema definition like email: { type: String, required: true, unique: true, background: true },
. I don't understand what they are trying to convey there.
This thread says that ...an index build can happen in the "background"...
but I don't see this confirmed in the mongoose documentation. Maybe I missed it or maybe the issue is not understanding when to refer to the mongoose documentation over the mongodb documentation when my application is using mongoose
to handle all mongodb
actions.