mongoose custom validation using 2 fields

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

    An an alternative to the accepted answer for the original question is:

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

提交回复
热议问题