Mongoose Validation Based on Other Fields

时间:2017-08-04 12:18:02

标签: node.js validation mongoose mongoose-schema

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?

1 个答案:

答案 0 :(得分:4)

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;
        }
    ]
},
相关问题