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
.