Model.ensureIndexes()

Parameters
  • [options] «Object» internal options

  • [cb] «Function» optional callback

Returns:
  • «Promise»

Sends createIndex commands to mongo for each index declared in the schema. The createIndex commands are sent in series.

Example:

  1. Event.ensureIndexes(function (err) {
  2. if (err) return handleError(err);
  3. });

After completion, an index event is emitted on this Model passing an error if one occurred.

Example:

  1. const eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  2. const Event = mongoose.model('Event', eventSchema);
  3. Event.on('index', function (err) {
  4. if (err) console.error(err); // error occurred during index creation
  5. })

NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.