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

时间:2017-05-16 04:59:33

标签: node.js mongodb mongoose database

我有两个模型设置:

ShopsModel

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

var ShopsModel = mongoose.model("Shops", ShopsSchema);

FieldGroupsModel

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)

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

我需要为FieldGroupsModel fields[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"
  }
}

第二条规则是第一条规则应仅适用于共享相同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"
  }
}

但是,这是有效的:

// 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"
  }
}

我对Mongo和Mongoose很陌生,所以任何帮助都会非常赞赏! :)

1 个答案:

答案 0 :(得分:2)

您调用Schema对象上的index方法,如图所示here。对于你的情况,它将是这样的:

FieldGroupsSchema.index({"shop": 1, "fields.handle": 1}, {unique: true});

有关详细信息,请阅读有关Compound Indexes的MongoDB文档。