7

Consider the following schema for saving time intervals in Mongoose:

let dateIntervalSchema = new mongoose.Schema({
  begin: { type: Date, required: true  },
  end: { type: Date, required: true }
})

How can I ensure that end is always greater than or equal to begin using Mongoose Validation?

Kayvan Mazaheri
  • 2,447
  • 25
  • 40

1 Answers1

17

I don't know if Mongoose has built-in validators for this, but something as small as the following can be used.

startdate: {
    type: Date,
    required: true,
    // default: Date.now
},
enddate: {
    type: Date,
    validate: [
        function (value) {
            return this.startdate <= value;
        }
    ]
},
Shane
  • 3,049
  • 1
  • 17
  • 18