基于其他字段的猫鼬验证

Kay*_*eri 6 validation mongoose node.js mongoose-schema

考虑以下用于在 Mongoose 中保存时间间隔的模式:

let dateIntervalSchema = new mongoose.Schema({
  begin: { type: Date, required: true  },
  end: { type: Date, required: true }
})
Run Code Online (Sandbox Code Playgroud)

如何确保end始终大于或等于begin使用猫鼬验证

Sha*_*ard 14

我不知道 Mongoose 是否为此内置了验证器,但可以使用像下面这样小的东西。

startdate: {
    type: Date,
    required: true,
    // default: Date.now
},
enddate: {
    type: Date,
    validate: [
        function (value) {
            return this.startdate <= value;
        }
    ]
},
Run Code Online (Sandbox Code Playgroud)