diff --git a/models/programs.js b/models/programs.js index 54b37679..a396cad7 100644 --- a/models/programs.js +++ b/models/programs.js @@ -49,12 +49,10 @@ const programSchema = new Schema({ startDate: { type: Date, index: true, - required: true, }, endDate: { type: Date, index: true, - required: true, }, translations: Object, source: { @@ -73,10 +71,16 @@ const programSchema = new Schema({ }, }) +const normalizeDate = (date) => (date ? new Date(date) : date) + // pre hook invoked before creating a document programSchema.pre('validate', function (next) { - if (this.startDate && this.endDate && this.startDate >= this.endDate) { - return next(new Error('startDate must be less than endDate')) + if (this.startDate && this.endDate) { + const startDate = normalizeDate(this.startDate) + const endDate = normalizeDate(this.endDate) + if (startDate >= endDate) { + return next(new Error('startDate must be less than endDate')) + } } next() }) @@ -86,8 +90,8 @@ programSchema.pre(['findOneAndUpdate', 'updateOne'], async function (next) { const update = this.getUpdate() const set = update.$set || {} - const startDate = set.startDate ?? update.startDate - const endDate = set.endDate ?? update.endDate + const startDate = normalizeDate(set.startDate ?? update.startDate) + const endDate = normalizeDate(set.endDate ?? update.endDate) // If both provided in update, validate directly if (startDate && endDate && new Date(startDate) >= new Date(endDate)) { diff --git a/models/solutions.js b/models/solutions.js index d5567efc..865b2d04 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -35,12 +35,10 @@ const solutionSchema = new Schema({ startDate: { type: Date, index: true, - required: true, }, endDate: { type: Date, index: true, - required: true, }, status: String, evidenceMethods: Object, @@ -126,10 +124,16 @@ const solutionSchema = new Schema({ }, }) +const normalizeDate = (date) => (date ? new Date(date) : date) + // pre hook invoked before creating a document solutionSchema.pre('validate', function (next) { - if (this.startDate && this.endDate && this.startDate >= this.endDate) { - return next(new Error('startDate must be less than endDate')) + if (this.startDate && this.endDate) { + const startDate = normalizeDate(this.startDate) + const endDate = normalizeDate(this.endDate) + if (startDate >= endDate) { + return next(new Error('startDate must be less than endDate')) + } } next() }) @@ -139,8 +143,8 @@ solutionSchema.pre(['findOneAndUpdate', 'updateOne'], async function (next) { const update = this.getUpdate() const set = update.$set || {} - const startDate = set.startDate ?? update.startDate - const endDate = set.endDate ?? update.endDate + const startDate = normalizeDate(set.startDate ?? update.startDate) + const endDate = normalizeDate(set.endDate ?? update.endDate) // If both provided in update, validate directly if (startDate && endDate && new Date(startDate) >= new Date(endDate)) {