在 Mongoose 中为对象数组创建索引

Tom*_*Tom 3 database mongoose mongodb node.js

我有两个模型设置:

店铺模型

var ShopsSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

var ShopsModel = mongoose.model("Shops", ShopsSchema);
Run Code Online (Sandbox Code Playgroud)

字段组模型

var FieldGroupsSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  fields: [{
    label: {
      type: String,
      required: true
    },
    handle: {
      type: String,
      required: true
    }
  }],
  shop: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Shops"
  }
});

var FieldGroupsModel = mongoose.model("FieldGroups", FieldGroupsSchema)
Run Code Online (Sandbox Code Playgroud)

每个 FieldGroups 实例都有一个与之关联的 ShopsModel。

我需要为 FieldGroupsModelfields[i].handle值创建一个索引,这个索引需要两个规则;它需要对每个 FieldGroupsModel 实例都是唯一的,因此此数据将无效:

{
  title: "Some field group title here",
  fields: [
    {
      label: "Some label 1"
      handle: "some-label-1"
    },
    {
      label: "Some label 1"
      handle: "some-label-1" // Error: `some-label-1` already exists as a value of `fields[i].handle`.
    }
  ],
  shop: {
    "$oid": "1"
  }
}
Run Code Online (Sandbox Code Playgroud)

第二条规则是第一条规则应该只适用于共享相同shop值的FieldGroupsModel 实例。所以这个数据将是无效的:

// First bit of data
{
  title: "Some field group title here",
  fields: [
    {
      label: "Some label 1"
      handle: "some-label-1"
    }
  ],
  shop: {
    "$oid": "1"
  }
}

// Second bit of data
{
  title: "Another field group title here",
  fields: [
    {
      label: "Some label 1"
      handle: "some-label-1" // Error: `some-label-1` already exists as a value of `fields[i].handle` of a document which shares the same `shop` value.
    }
  ],
  shop: {
    "$oid": "1"
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,这将是有效的:

// First bit of data
{
  title: "Some field group title here",
  fields: [
    {
      label: "Some label 1"
      handle: "some-label-1"
    }
  ],
  shop: {
    "$oid": "1"
  }
}

// Second bit of data
{
  title: "Another field group title here",
  fields: [
    {
      label: "Some label 1"
      handle: "some-label-1" // This is valid because there's no other documents with the same `shop` value with the same `fields[i].handle` value.
    }
  ],
  shop: {
    "$oid": "2"
  }
}
Run Code Online (Sandbox Code Playgroud)

我是很新的蒙戈和猫鼬所以这里的任何帮助将大大感激!:)

Đức*_*yễn 7

你叫index你的架构对象上的方法来做到这一点,如图在这里。对于您的情况,它将类似于:

FieldGroupsSchema.index({"shop": 1, "fields.handle": 1}, {unique: true});
Run Code Online (Sandbox Code Playgroud)

请阅读有关复合索引的 MongoDB 文档以获取更多详细信息。