Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose custom validation using 2 fields

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.

like image 902
amgohan Avatar asked May 20 '14 12:05

amgohan


1 Answers

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. 

like image 64
JohnnyHK Avatar answered Sep 30 '22 03:09

JohnnyHK