gpt4 book ai didi

node.js - 所需的子文档 Mongoose

转载 作者:可可西里 更新时间:2023-11-01 09:34:13 26 4
gpt4 key购买 nike

我定义了以下 Mongoose 模式

var subSchema = new Schema({
propertySub: {type: String, required: true}
});

var mainSchema = new Schema({
mainProperty: {type: String, required: true},
subs: [subSchema]
});

如您所见,subSchema 上有一个必需的属性,问题是我希望 mainSchema 需要至少有一个 subSchema ,但是当我发送

{
"mainProperty" : "Main"
}

没有失败。

我试过类似的东西

subs: [{
type: subSchema,
required: true
}]

但它会抛出以下内容:

TypeError: Undefined type undefined at array subs

所以无论如何都要这样做?,也许用 validate 我是 node 和 mongoose 的新手,所以非常感谢解释

最佳答案

是的,您要么想要使用验证,要么可以根据需要使用预保存 Hook 进行验证。这是使用验证的示例

var mainSchema = new Schema({
mainProperty: {type: String, required: true},
subs: {
type: [subSchema],
required: true,
validate: [notEmpty, "Custom error message"]
}
});

function notEmpty(arr) {
return arr.length > 0;
}

关于node.js - 所需的子文档 Mongoose ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43037643/

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