SchemaType.prototype.index()

Parameters
  • options «Object|Boolean|String»
Returns:
  • «SchemaType» this

Declares the index options for this schematype.

Example:

  1. const s = new Schema({ name: { type: String, index: true })
  2. const s = new Schema({ loc: { type: [Number], index: 'hashed' })
  3. const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
  4. const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
  5. const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
  6. s.path('my.path').index(true);
  7. s.path('my.date').index({ expires: 60 });
  8. s.path('my.path').index({ unique: true, sparse: true });

NOTE:

Indexes are created in the background by default. If background is set to false, MongoDB will not execute any read/write operations you send until the index build. Specify background: false to override Mongoose’s default.