Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possibly unhandled CastError: Cast to date failed for value "function now() { [native code] } on Mongoose

I'm getting the following error when running Express app

Possibly unhandled CastError: Cast to date failed for value "function now() { [native code] }

The date field is defined on model as:

updated: {
  type: Date,
  default: Date.now
}

So, I'm logging the response and the field comes with this format

updated: Thu May 21 2015 16:21:32 GMT-0300 (ART)

Actually we've using Mongoose v 3.4.0

I've also tried to format the response with Moment.js but the warning still appears on the terminal.

I've would appreciate your help.

like image 567
Ezequiel Miranda Avatar asked Nov 01 '22 03:11

Ezequiel Miranda


1 Answers

Old question but as mentioned by Ken, to create or update provide the Schema/Model with the Date value

sendHelpDate: Date.now()

This will save to the DB as "sendHelpDate" : ISODate("2018-06-27T10:49:29.328+0000"), as opposed to passing the function of Date.now see below:

    message: 'Cast to Date failed for value "[Function: now]" at 
    path "sendHelpDate"',
    name: 'CastError',        
    stringValue: '"[Function: now]"',
    kind: 'Date',
    value: [Function: now],
    path: 'sendHelpDate',
    reason: [Object]                                                         
    _message: 'Bookings validation failed', 
    name: 'ValidationError' }

Hope the extra detail will help someone in future

like image 53
Jerome Hurley Avatar answered Nov 15 '22 06:11

Jerome Hurley