【发布时间】:2014-09-15 00:43:57
【问题描述】:
我在 Mongoose 中使用架构作为子文档,但我无法在其字段中对其进行验证。
这就是我所拥有的
var SubdocumentSchema = new Schema({
foo: {
type: String,
trim: true,
required: true
},
bar: {
type: String,
trim: true,
required: true
}
});
var MainDocumentSchema = new Schema({
name: {
type: String,
trim: true,
required: true
},
children: {
type : [ SubdocumentSchema.schema ],
validate: arrayFieldsCannotBeBlankValidation
}
});
我想确保子文档的每个字段都不为空。
我发现用标准方法验证数组是不可能的,所以我编写了我的自定义验证函数。
到目前为止,我必须手动检查所有字段是否正确且不为空,但在我看来,这不是一个真正可扩展的解决方案,所以我想知道是否有一些本机方法可以从 MainDocument 触发子文档验证。
【问题讨论】:
-
我很高兴看到你的验证函数
arrayFieldsCannotBeBlankValidation它会验证数组中的每个对象吗?例如:它会用MainDocumentSchema.children.name检查任何重复值吗? -
我真的不记得了,代码已经很久以前了。对不起!
标签: node.js mongodb validation mongoose