{"record":{"id":"97958d76fcf56dce","repo":"Automattic/mongoose","slug":"cast-to-int32-failed-for-value-value-type","errorCode":null,"errorMessage":"Cast to Int32 failed for value \"${value}\" (type ${valueType}) at path \"${path}\"","messagePattern":"Cast to Int32 failed for value \"(.+?)\" \\(type (.+?)\\) at path \"(.+?)\"","errorType":"exception","errorClass":"CastError","httpStatus":null,"severity":"error","filePath":"lib/schema/int32.js","lineNumber":193,"sourceCode":" * @param {object} value\n * @param {object} model this value is optional\n * @api private\n */\n\nSchemaInt32.prototype.cast = function(value) {\n  let castInt32;\n  if (typeof this._castFunction === 'function') {\n    castInt32 = this._castFunction;\n  } else if (typeof this.constructor.cast === 'function') {\n    castInt32 = this.constructor.cast();\n  } else {\n    castInt32 = SchemaInt32.cast();\n  }\n\n  try {\n    return castInt32(value);\n  } catch (error) {\n    throw new CastError('Int32', value, this.path, error, this);\n  }\n};\n\n/*!\n * ignore\n */\n\nconst $conditionalHandlers = {\n  ...SchemaType.prototype.$conditionalHandlers,\n  $gt: handleSingle,\n  $gte: handleSingle,\n  $lt: handleSingle,\n  $lte: handleSingle,\n  $bitsAllClear: handleBitwiseOperator,\n  $bitsAnyClear: handleBitwiseOperator,\n  $bitsAllSet: handleBitwiseOperator,\n  $bitsAnySet: handleBitwiseOperator\n};","sourceCodeStart":175,"sourceCodeEnd":211,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/schema/int32.js#L175-L211","documentation":"SchemaInt32.cast converts failures of the Int32 caster (lib/cast/int32.js) into this CastError. Valid input: null/undefined, empty string (→ null), BSON Long, and anything Number() coerces to an integer within [-2147483648, 2147483647]. Arrays, non-integer values (1.5), and out-of-range integers (3000000000, millisecond timestamps) throw.","triggerScenarios":"`doc.count = 1.5` (non-integer), `doc.count = 3000000000` (exceeds 2^31-1), `doc.count = [1]` (array), `doc.count = 'abc'`, or a Long larger than Int32 range. Query side: `{ count: { $gt: 'big' } }`.","commonSituations":"Counters and view stats overflowing Int32; Date.now() millisecond timestamps stored in an Int32 path (they need Long or Number); user input with decimals; migrating a Number path to Int32 while existing data exceeds the range; negative overflow from signed math.","solutions":["Use `mongoose.Schema.Types.Long` or plain `Number` for values that can exceed ±2^31; Int32 is only for guaranteed-small integers","Round before assigning: `doc.count = Math.trunc(v)` and range-check the result","Validate at the boundary: `Number.isInteger(v) && v >= -2147483648 && v <= 2147483647`","Store timestamps as `Schema.Types.Date` instead of numeric epochs"],"exampleFix":"// before\nevent.ts = { type: mongoose.Schema.Types.Int32 }; // then: event.ts = Date.now();\n\n// after\nevent.ts = { type: Date }; // or Schema.Types.Long for epoch millis\nevent.ts = Date.now();","handlingStrategy":"type-guard","validationCode":"const INT32_MIN = -0x80000000, INT32_MAX = 0x7FFFFFFF;\nfunction isInt32(v) {\n  if (v == null || v === '') return true;\n  if (Array.isArray(v)) return false;\n  const n = typeof v === 'number' ? v : Number(v);\n  return Number.isInteger(n) && n >= INT32_MIN && n <= INT32_MAX;\n}\nif (!isInt32(req.body.count)) throw new Error('count must be a 32-bit integer');","typeGuard":"function isInt32Value(v) {\n  return Number.isInteger(v) && v >= -0x80000000 && v <= 0x7FFFFFFF;\n}","tryCatchPattern":"try { doc.count = v; } catch (err) { if (err.name === 'CastError' && err.kind === 'Int32') { return badRequest(`${err.path} must be an integer in [-2147483648, 2147483647]`); } throw err; }","preventionTips":["Use Long or Date for epoch millis, never Int32","Range-check counters that can grow unbounded","Math.trunc decimals before assigning to Int32 paths"],"tags":["mongoose","int32","cast","integer-overflow","validation"],"backgroundTag":"mongoose-cast-error","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}