Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Casting error in mongoose with node.js

Date Casting issue while inserting data to mongoDB using mongoose.

Model Looks Like this :

var userSchema = new Schema({
emailid: String,
createddate: Date,
status: String});

The value i am trying to save

{ emailid: '[email protected]',
  status: 'Activv',
  createddate: '24/01/2014' }

Error :

{ message: 'Cast to date failed for value "24/01/2014" at path "createddate"',
  name: 'CastError',type: 'date',value: "24/01/2014",path: 'createddate' }

I tried new Date(Date.parse(userObject. createddate))

like image 313
Binish Mookken Avatar asked Feb 20 '26 01:02

Binish Mookken


1 Answers

The CastError is throwed due to the date string 24/01/2014 is not a valid date format for mongoDB. MongoDB uses ISODate as the Date format. The solution for this problem is convert the date 24/01/2014 to 01/24/2014. This can be done easily with a npm module called moment.js.

like image 78
labkode Avatar answered Feb 21 '26 17:02

labkode