document.invalidate将空json作为响应

时间:2016-08-28 14:55:33

标签: express mongoose

我想检查文档中的body是否唯一。如果不唯一则给出适当的错误。

NewsSchema.pre("save", true, function (next: any, done: any) {
    var self = this;
    News.findOne({body: self.body}, "body", function (err: any, body: string) {
        if(err)
             done(err);
        else if(body) {
            self.invalidate("body", "the news body already exists", self.body);
            done(new Error("the news body already exists"));
        }
        else {
            next();
        }
   });
});

故意给出重复的body。它返回一个空的json。虽然我期待它:

{ 
    message: 'Validation failed',
    name: 'ValidationError',
    errors:
    { 
        size:
        {
            message: 'the news body already exists',
            name: 'ValidatorError',
            path: 'body',
            type: 'String',
            value: 'some string'
         } 
     } 
}

1 个答案:

答案 0 :(得分:0)

您需要使用validate()来检查它是否有效。

var self = this; //type document
...
self.invalidate("body", "the news body already exists", self.body);

//use validate() to check the validity
self.validate(function(err){
    console.log(err);//this will give you your expected results.
});