mongoose custom validation using 2 fields

后端 未结 6 1501
余生分开走
余生分开走 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:34

    This is the solution I used (thanks to @shakinfree for the hint) :

    var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
    
    // schema definition
    var ASchema = new Schema({
      dateSchema : {
                    type:{
                        startDate:{type:Date, required: true}, 
                        endDate:{type:Date, required: true}
                    }, 
                    required: true, 
                    validate: [dateValidator, 'Start Date must be less than End Date']
                }
    });
    
    // function that validate the startDate and endDate
    function dateValidator (value) {
        return value.startDate <= value.endDate;
    }
    
    module.exports = mongoose.model('A', ASchema);
    

提交回复
热议问题