簡體   English   中英

在Mongoose中為對象數組創建索引

[英]Create index in Mongoose for array of objects

我有兩個模型設置:

商店模型

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

我是很新的蒙戈和貓鼬所以這里的任何幫助將不勝感激! :)

您調用index你的架構對象上的方法來做到這一點,如圖在這里 對於您的情況,它將類似於:

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

請閱讀有關復合索引的MongoDB文檔以獲取更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM