Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 doesn't work; I get undefined.

var a = new Schema({ 

startDate: Date, 

endDate: Date 

}); 

var A = mongoose.model('A', a); A.schema.path('endDate').validate(function (value) {

return diff(this.startDate, value) >= 0; 

}, 'End Date must be greater than Start Date');

diff is a function that compares two dates.

2 Answers

0 votes
by (106k points)

In 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. 

0 votes
by (107k points)
edited by

Just use Mongoose 'validate' middleware so that you can have access to all fields of the collection. You have to keep one thing in mind that you must wrap all the messages of the validation errors in a JavaScript error object while calling the 'next' function for reporting a validation failure. 

ASchema.pre('validate', function(next) {

    if (this.startDate < this.endDate) {

        next(new Error('End Date must be smaller than Start Date'));

    } else {

        next();

    }

});

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...