我的模式是:
const testSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: [true, 'Name is required'],
maxlength: [40, 'Name should not be more than 40 characters'],
},
startDate: {
type: Date,
validate: {
validator: function (val) {
return moment(val) < moment(this.endDate);
},
message:
'({VALUE}) is not valid since the start date should not be ahead of end date',
},
required: [true, 'Start date is required'],
},
endDate: {
type: Date,
validate: {
validator: function (val) {
return moment(val) > moment(this.startDate);
},
message:
'({VALUE}) is not valid since the end date should be before start date',
},
required: [true, 'End date is required'],
},
});
在这里,我希望startDate
不大于endDate
,因为我需要访问另一个date属性。我正在尝试使用this.propertyName
访问文档,但是当我尝试undefined
时却得到了console.log(this.endDate)
。
我也尝试使用pre-validate挂钩,但是它仅在创建新文档时才触发,而不在更新时触发。我希望以上验证可以同时在创建和更新上运行。我怎样才能做到这一点?请帮忙