validationMongoose中的子文档
我在Mongoose中使用Schema作为子文档,但是我无法在其字段中对其进行validation。
这就是我所拥有的
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 } });
我想确保子文档的每个字段都不是空的。
我发现这不可能用标准方法来validation数组,所以我写了我的自定义validation函数。 现在我必须手动检查所有的字段是正确的,而不是空的,但它看起来像一个不是真正可扩展的解决scheme,所以我想知道是否有一些本地方法来触发从MainDocument一个子文档validation。
在children
的定义中,应该是[SubdocumentSchema]
,而不是[SubdocumentSchema.schema]
:
var MainDocumentSchema = new Schema({ name: { type: String, trim: true, required: true }, children: { type : [ SubdocumentSchema ], validate: arrayFieldsCannotBeBlankValidation } });
SubdocumentSchema.schema
评估为undefined
所以在您当前的代码Mongoose没有必要的types信息来validation子元素。