所需的子文档猫鼬

Required subdocuments Mongoose

我定义了以下 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 我是节点和猫鼬的新手,所以非常感谢解释

是的,您要么想要使用验证,要么可以根据需要使用预保存挂钩进行验证。这是一个使用 validate

的例子
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;
}