Search code examples
node.jsmongodbmongoose

Cast to date failed for value "Invalid Date" (type Date)


I have mongoose model I have made a model

const purchaseSchema = new mongoose.Schema(
  {
    studentId: { type: mongoose.Schema.Types.ObjectId, ref: "Student" },
    courseId: { type: mongoose.Schema.Types.ObjectId, ref: "course" },
    enrollmentDate: {
      type: Date,
    },
    expiryDate: {
      type: Date,
    },
    courseProgress: {
      type: Number,
    }
  },
  {
    timestamps: true,
  }
);

I have deployed my code on render and trying to create a record using this model and the code for that is

let tod = new Date(Date.now());
let expDate = new Date(tod);
const today = tod.toISOString(); // Convert to ISODate string
expDate.setMonth(expDate.getMonth() + course.validity);
const expiryDate = expDate.toISOString();
// Create enrollment record
const purchase = await purchaseModel.create({
          studentId: student_id,
          courseId: course_id,
          enrollmentDate: today,
          expiryDate: expiryDate,
          progress: 0,
});

but it is giving me this error

Error: Purchase validation failed: expiryDate: Cast to date failed for value "Invalid Date" (type Date) at path "expiryDate"
    at ValidationError.inspect (/opt/render/project/src/node_modules/mongoose/lib/error/validation.js:50:26)

I have tested the same code on my local system it running fine but the deployed version is giving me this error.


Solution

  • Your model requires a Date, however you run .toISOString() which returns a string, this does not work.

    When you have to work with dates, then I recommend a 3rd part library, like moment, luxon or day.js. Would be like this one:

    const { DateTime } = require("luxon");
    const purchase = await purchaseModel.create({
              studentId: student_id,
              courseId: course_id,
              enrollmentDate: DateTime.now().toJSDate(),
              expiryDate: DateTime.now().plus({ months: course.validity }).toJSDate(),
              progress: 0,
    });