{"record":{"id":"6e7bffad238a6e5a","repo":"Automattic/mongoose","slug":"cast-to-date-failed-for-value-value-type-v","errorCode":null,"errorMessage":"Cast to date failed for value \"${value}\" (type ${valueType}) at path \"${path}\"","messagePattern":"Cast to date failed for value \"(.+?)\" \\(type (.+?)\\) at path \"(.+?)\"","errorType":"exception","errorClass":"CastError","httpStatus":null,"severity":"error","filePath":"lib/schema/date.js","lineNumber":380,"sourceCode":" *\n * @param {object} value to cast\n * @api private\n */\n\nSchemaDate.prototype.cast = function(value) {\n  let castDate;\n  if (typeof this._castFunction === 'function') {\n    castDate = this._castFunction;\n  } else if (typeof this.constructor.cast === 'function') {\n    castDate = this.constructor.cast();\n  } else {\n    castDate = SchemaDate.cast();\n  }\n\n  try {\n    return castDate(value);\n  } catch (error) {\n    throw new CastError('date', value, this.path, error, this);\n  }\n};\n\n/**\n * Date Query casting.\n *\n * @param {any} val\n * @api private\n */\n\nfunction handleSingle(val) {\n  return this.cast(val);\n}\n\nconst $conditionalHandlers = {\n  ...SchemaType.prototype.$conditionalHandlers,\n  $gt: handleSingle,\n  $gte: handleSingle,","sourceCodeStart":362,"sourceCodeEnd":398,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/schema/date.js#L362-L398","documentation":"SchemaDate.cast wraps the date caster (lib/cast/date.js) and converts any failure into a CastError of type 'date'. The caster accepts Date instances (rejected if Invalid Date), numbers and numeric millisecond strings, moment-like objects via valueOf(), and any string the Date constructor can parse; it explicitly rejects booleans and everything that yields NaN. null/undefined and empty string pass through as null.","triggerScenarios":"`doc.createdAt = 'yesterday'` (unparseable string), `doc.d = true` (booleans asserted against), `doc.d = new Date('nope')` (Invalid Date instance), a moment-like object whose valueOf() returns NaN, or a string like '12/34/2024' whose Date parse yields NaN. Also `Model.find({ createdAt: { $gt: 'gibberish' } })` via handleSingle.","commonSituations":"Free-text form inputs mapped straight onto Date paths; locale-formatted dates ('31/02/2024', 'dd.mm.yyyy') that Date.parse cannot handle; third-party APIs returning non-ISO date strings; booleans leaking in from truthy/falsy flag logic.","solutions":["Normalize input before assigning: `const d = new Date(input); if (Number.isNaN(d.getTime())) throw ...`","Use a proper date parser (dayjs/moment with a format string) for locale-specific strings, then assign `.toDate()`","Register a global custom caster with `mongoose.Schema.Types.Date.cast(v => ...)` that accepts your formats and throws on garbage","Reject boolean/truthy values at the request-validation boundary"],"exampleFix":"// before\nuser.dob = req.body.dob; // '05/03/2024' or free text\n\n// after\nconst dob = dayjs(req.body.dob, 'DD/MM/YYYY').toDate();\nif (Number.isNaN(dob.getTime())) throw new ValidationError('bad dob');\nuser.dob = dob;","handlingStrategy":"validation","validationCode":"function toSafeDate(v) {\n  if (v == null || v === '') return null;\n  if (v instanceof Date) { if (Number.isNaN(v.getTime())) throw new Error('invalid Date'); return v; }\n  if (typeof v === 'boolean') throw new Error('boolean is not a date');\n  const d = new Date(typeof v.valueOf === 'function' ? v.valueOf() : v);\n  if (Number.isNaN(d.getTime())) throw new Error(`unparseable date: ${v}`);\n  return d;\n}","typeGuard":"function isDateLike(v) {\n  return v == null || v === '' || v instanceof Date || typeof v === 'number' ||\n    (typeof v === 'string' && !Number.isNaN(new Date(v).getTime()));\n}","tryCatchPattern":"try { doc.when = value; } catch (err) { if (err.name === 'CastError' && err.kind === 'date') { return badRequest(`invalid date for ${err.path}`); } throw err; }","preventionTips":["Parse locale formats with dayjs/moment and a format string, then assign .toDate()","Never map boolean flags onto date paths","Validate date strings at the request boundary with a strict ISO-8601 check"],"tags":["mongoose","date","cast","validation","date-parsing"],"backgroundTag":"mongoose-cast-error","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}