Mongoosejs验证未定义属性

Mongoosejs验证未定义属性,mongoose,Mongoose,如果我有这样一条规则: CommentSchema.path('body').validate(function(body) { return body.length; }, 'Body cannot be empty'); 例如,如果我这样做: curl -d "author=Kris" \ -d "email=Jordan" \ http://localhost:3000/api/comment 服务器崩溃,并显示以下错误消息: Cannot read property 'len

如果我有这样一条规则:

CommentSchema.path('body').validate(function(body) {
    return body.length;
}, 'Body cannot be empty');
例如,如果我这样做:

curl -d "author=Kris" \
-d "email=Jordan" \
http://localhost:3000/api/comment
服务器崩溃,并显示以下错误消息:

Cannot read property 'length' of undefined
所以我想知道是否有一种方法可以避免所有的时间 在每项规则中)做:


您应该能够将其简化为:

CommentSchema.path('body').validate(函数(body)){
返回!!身体;
},“正文不能为空”);

并不是严格必需的,但它通过显式地将
body
作为布尔值进行计算,有助于澄清发生了什么<代码>空、
未定义
'
都计算为假。

正文和正文。长度
是另一种选择。
CommentSchema.path('body').validate(function(body) {
    if(typeof body !== "undefined" && body !== null){
        return body.length > 0
    }
    return false;
}, 'Body cannot be empty');