gpt4 book ai didi

node.js - 在 Mongoose 中为对象数组创建索引

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:50 25 4
gpt4 key购买 nike

我有两个模型设置:

商店模型

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

我是 Mongo 和 Mongoose 的新手,所以我将非常感谢任何帮助! :)

最佳答案

您调用 Schema 对象上的 index 方法来执行此操作,如图所示 here .对于您的情况,它将类似于:

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

请阅读有关 Compound Indexes 的 MongoDB 文档了解更多详情。

关于node.js - 在 Mongoose 中为对象数组创建索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43992823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com