2014-07-23 57 views
1

我在Mongoose中使用Schema作为子文档,但我无法在其字段中验证它。
这就是我验证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触发子文档验证。

回答

4

children的定义,它应该是[SubdocumentSchema],不[SubdocumentSchema.schema]

var MainDocumentSchema = new Schema({ 
    name: { 
    type: String, 
    trim: true, 
    required: true 
    }, 
    children: { 
    type : [ SubdocumentSchema ], 
    validate: arrayFieldsCannotBeBlankValidation 
    } 
}); 

SubdocumentSchema.schema计算结果为undefined所以在当前的代码猫鼬不具备必要的类型信息来验证的children的元素。

+0

谢谢你。我搞乱了一切,试图在数组上运行自定义验证,认为问题出在那里,而这正是我调用模式的方式。你救了我。 – pasine