title: Specify an Index Name with Mongoose
body: <p>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.  </p>
  
  <p>Indeed, when creating certain indexes, specifying an index name explicitly is required to avoid exceeding the <a href="https://docs.mongodb.com/manual/reference/limits/#Index-Name-Length" rel="noreferrer"><code>index name length limit</code></a>.</p>
  
  <p>Since <strong><a href="https://docs.mongodb.com/manual/reference/method/db.collection.ensureIndex/" rel="noreferrer"><code>ensureIndex</code></a></strong> 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?</p>
  
  <pre><code>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});
  </code></pre>
  
  <p>It is worth noting that <a href="https://docs.mongodb.com/manual/reference/method/db.collection.ensureIndex/" rel="noreferrer"><code>db.collection.ensureIndex</code></a> is deprecated (by mongodb), and is now an alias for <a href="https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex" rel="noreferrer"><code>db.collection.createIndex</code></a>.</p>