mongoose custom validation using 2 fields

后端 未结 6 1500
余生分开走
余生分开走 2020-11-27 05:00

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 d

6条回答
  •  遥遥无期
    2020-11-27 05:23

    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}
    });
    

提交回复
热议问题