[英]Create index in Mongoose for array of objects
我有兩個模型設置:
var ShopsSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
var ShopsModel = mongoose.model("Shops", ShopsSchema);
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"
}
}
我是很新的蒙戈和貓鼬所以這里的任何幫助將不勝感激! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.