mongoose custom validation using 2 fields
express, mongodb, mongoose, node.js
Solution
You could try nesting your date stamps in a parent object and then validate the parent. For example something like:
//create a simple object defining your dates
var dateStampSchema = {
startDate: {type:Date},
endDate: {type:Date}
};
//validation function
function checkDates(value) {
return value.endDate < value.startDate;
}
//now pass in the dateStampSchema object as the type for a schema field
var schema = new Schema({
dateInfo: {type:dateStampSchema, validate:checkDates}
});
Problem
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.