Reputation: 363
If I have a property in my schema that depends on another one (like it's minimum value), how do define that in my schema?
I have an endDate and an actualEndDate properties in my schema, the second one will always be greater than or equal to the first one, how do I put that in my schema
const schema = new mongoose.Schema({
endDate: {
type: Date,
min: new Date(),
required: true
},
actualEndDate: {
type: Date,
min: new Date(), // I need this to be min: this.endDate or something
}
});
Upvotes: 4
Views: 1854
Reputation: 1592
You can add your own custom validation.
Try this:
endDate: {
type: Date,
required: true,
// min: new Date()
// default: Date.now
},
actualEndDate: {
type: Date,
validate: [
function (value) {
return this.endDate <= value;
}
]
},
Upvotes: 2
Reputation: 23029
before you save/update any document you can add pre-save hooks that can check the validity of document and throw error or update some value based on your logic.
https://mongoosejs.com/docs/middleware.html#pre
Upvotes: 0