mongoose custom validation using 2 fields

后端 未结 6 1519
余生分开走
余生分开走 2020-11-27 05:00

I want to use mongoose custom validation to validate if endDate is greater than startDate. How can I access startDate value? When using this.startDate, it d

6条回答
  •  忘掉有多难
    2020-11-27 05:30

    You can do that using Mongoose 'validate' middleware so that you have access to all fields:

    ASchema.pre('validate', function(next) {
        if (this.startDate > this.endDate) {
            next(new Error('End Date must be greater than Start Date'));
        } else {
            next();
        }
    });
    

    Note that you must wrap your validation error message in a JavaScript Error object when calling next to report a validation failure. 

提交回复
热议问题