Don Scott
Don Scott

Reputation: 3457

Specify an Index Name with Mongoose

When defining a Mongoose schema it is often prudent to specify what indexes should exist. That said, in many cases we would like to control the name of the index created, especially when those indexes are compound so they are understandable.

Indeed, when creating certain indexes, specifying an index name explicitly is required to avoid exceeding the index name length limit.

Since ensureIndex is called (by default) on indexes defined in the schema, what is the appropriate syntax to control the name of an index created by ensureIndex? I assume this is impossible with the field level index syntax, but surely it is available for schema level indexes?

var ExampleSchema = new Schema({
  a: String,
  b: String,
  c: Date,
  d: Number,
  e: { type: [String], index: true } // Field level index
});

// We define compound indexes in the schema
ExampleSchema.index({a: 1, b: 1, c: 1});
ExampleSchema.index({d:1, e:1}, {unique: true});

It is worth noting that db.collection.ensureIndex is deprecated (by mongodb), and is now an alias for db.collection.createIndex.

Upvotes: 8

Views: 9729

Answers (2)

Don Scott
Don Scott

Reputation: 3457

It turns out that Mongoose wraps the Mongo driver fairly transparently.

As such, a call to <Mongoose.Schema>.index(<keys>, <options>) can be roughly interpreted to result in a call to db.collection.ensureIndex(keys, options) or db.collection.createIndex(keys, options) in Mongo 3.0+.

Hence, the required syntax (while poorly undocumented) is identical to the MongoDB syntax for schema index declarations.

That is, we declare names as follows:

ExampleSchema.index({a: 1, b: 1, c: 1}, {name: "ExampleIndexName_ABC"});
ExampleSchema.index({d:1, e:1}, {unique: true, name: "ExampleCompoundIndexName"});

Options are also include:

  • background
  • unique
  • name
  • partialFilterExpression
  • sparse
  • expireAfterSeconds
  • storageEngine

See the official MongoDB documents for details.

Upvotes: 4

JohnnyHK
JohnnyHK

Reputation: 311865

You can set the name of the index using the name property of the option parameter of the index call:

ExampleSchema.index({a: 1, b: 1, c: 1}, {name: 'my_index'});
ExampleSchema.index({d:1, e:1}, {name: 'my_other_index', unique: true});

As noted in the docs, the second parameter of index contains the:

Options to pass to MongoDB driver's createIndex() function

The createIndex doc list all the possible option settings, including name.

Upvotes: 9

Related Questions