mongoose custom validation using 2 fields

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. 

Leave a Comment