使用 Mongoose 指定索引名称

Specify an Index Name with Mongoose

定义 Mongoose 模式时,通常需要谨慎指定应存在哪些索引。也就是说,在许多情况下,我们希望控制所创建索引的名称,尤其是当这些索引是复合的以便可以理解时。

确实,在创建某些索引时,需要明确指定索引名称,以避免超过index name length limit

由于 ensureIndex 是在模式中定义的索引上调用的(默认情况下),控制 ensureIndex 创建的索引名称的适当语法是什么?我认为这对于字段级索引语法是不可能的,但它肯定可用于模式级索引吗?

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});

值得注意的是db.collection.ensureIndex is deprecated (by mongodb), and is now an alias for db.collection.createIndex.

您可以使用 index 调用的选项参数的 name 属性 设置索引的名称:

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

docs 中所述,index 的第二个参数包含:

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

createIndex 文档列出了所有可能的选项设置,包括 name

事实证明 Mongoose 相当透明地包装了 Mongo 驱动程序。

因此,对<Mongoose.Schema>.index(<keys>, <options>)的调用可以粗略地解释为在[=56中调用db.collection.ensureIndex(keys, options) or db.collection.createIndex(keys, options) =] 3.0+.

因此,所需的语法(虽然未记录在案)与 schema 索引声明的 MongoDB 语法相同。

即我们声明名称如下:

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

选项还包括:

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

详情见official MongoDB documents