我想使用猫鼬自定义验证来验证endDate是否大于startDate。如何访问startDate值?使用 this.startDate时 ,它不起作用;我不确定。
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 是比较两个日期的函数。
diff
您可以尝试将日期戳嵌套在父对象中,然后验证父对象。例如:
//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} });