嵌套文档中字段上的猫鼬索引

Pra*_*dra 9 mongoose mongodb node.js

我有一个小架构

var PostSchema = new mongoose.Schema({
  title: String,
  link: String,
  author: {type:String,required:true},
  upvotes: {type: Number, default: 0},
  nesteddoc : {
      field1: String
  }
});

//This is broken - index on field1
PostSchema.index({nesteddoc.field1:1},{unique:true});
Run Code Online (Sandbox Code Playgroud)

通过在 Mongoose 模式中指定而不运行 MongoDB 查询来确保索引,是否可以在嵌套字段上创建索引?

Ber*_*tel 13

使用引号"nesteddoc.field1"来评估嵌套字段:

PostSchema.index({ "nesteddoc.field1": 1 }, { unique: true });
Run Code Online (Sandbox Code Playgroud)

此外,mongoose 会ensureIndexmongoose doc内部调用:

当您的应用程序启动时,Mongoose 会自动为架构中定义的每个索引调用 ensureIndex。Mongoose 将依次为每个索引调用 ensureIndex,并在所有 ensureIndex 调用成功或出现错误时在模型上发出 'index' 事件。虽然有利于开发,但建议在生产中禁用此行为,因为索引创建会导致显着的性能影响。通过将架构的 autoIndex 选项设置为 false 来禁用该行为,或者通过将选项 config.autoIndex 设置为 false 在连接上全局禁用该行为。

您还可以在架构中定义索引:

var PostSchema = new mongoose.Schema({
    title: String,
    link: String,
    author: { type: String, required: true },
    upvotes: { type: Number, default: 0 },
    nesteddoc: {
        field1: { type: String, unique: true, index: true },
    }
});
Run Code Online (Sandbox Code Playgroud)