I use Mongoose in my project and in one of the schemas I use Date field, like this:
reservationDay: {
type: Date,
default: Date.now
}
I can create document with this field without a problem. And when I console.log this date after it has been created I get:
reservationDay: Thu Nov 20 2014 04:45:00 GMT+0100 (CET)
However, there is a problem when I try tu update this document (even without changing reservationDay field). Here is the error message I get:
name: 'CastError',
message: 'Cast to date failed for value "20/11/2014 04:11" at path "reservationDay"' } CastError: Cast to date failed for value "20/11/2014 04:11" at path "reservationDay"
Here is how I update this document on server side:
Reservation.findOne({ _id: id }).exec(function(err, reservation) {
if (err) {
//handle
}
if (!reservation) {
//handle
}
reservation = extend(reservation, req.body);
reservation.save(function(err, updatedReservation) {
if (err) {
//handle
}
return res.json(reservation);
});
});
and the date is not changed in the req.body.
Any ideas what might cause this error?
Thanks!
"20/11/2014 04:11"
is an invalid ISODate format. Somewhere you are converting reservationDate into a string of an invalid format. You need to convert it to a valid ISODate format (month before day):
new Date("11/20/2014 04:11") // Thu Nov 20 2014 04:11:00 GMT+0100 (CET)
new Date("2014/11/20 04:11") // Thu Nov 20 2014 04:11:00 GMT+0100 (CET)
new Date("20/11/2014 04:11") // Invalid Date
for easy manipulation of date formats, I'd recommend using moment.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With