我在 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
}
});
我想确保子文档的每个字段都不为空。
我发现无法使用标准方法验证数组,因此我编写了自定义验证函数。
现在,我必须手动检查所有字段是否正确且不为空,但在我看来,这并不是一个真正可扩展的解决方案,因此我想知道是否有某种 native 方法可以从 MainDocument 触发子文档验证。
最佳答案
在children
的定义中,应该是[SubdocumentSchema]
,而不是[SubdocumentSchema.schema]
:
var MainDocumentSchema = new Schema({
name: {
type: String,
trim: true,
required: true
},
children: {
type : [ SubdocumentSchema ],
validate: arrayFieldsCannotBeBlankValidation
}
});
SubdocumentSchema.schema
计算结果为 undefined
,因此在您当前的代码中,Mongoose 没有必要的类型信息来验证 children
的元素.
关于node.js - 验证 Mongoose 中的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917143/