Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Cast to date failed for value when updating a document

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!

like image 541
Jakub Avatar asked Dec 09 '22 05:12

Jakub


1 Answers

"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

like image 77
chrisbajorin Avatar answered Dec 28 '22 23:12

chrisbajorin