{"record":{"id":"330675c03113bdb1","repo":"Automattic/mongoose","slug":"cast-to-bigint-failed-for-value-value-type","errorCode":null,"errorMessage":"Cast to BigInt failed for value \"${value}\" (type ${valueType}) at path \"${path}\"","messagePattern":"Cast to BigInt failed for value \"(.+?)\" \\(type (.+?)\\) at path \"(.+?)\"","errorType":"exception","errorClass":"CastError","httpStatus":null,"severity":"error","filePath":"lib/schema/bigint.js","lineNumber":173,"sourceCode":" * @param {object} value\n * @param {object} model this value is optional\n * @api private\n */\n\nSchemaBigInt.prototype.cast = function(value) {\n  let castBigInt;\n  if (typeof this._castFunction === 'function') {\n    castBigInt = this._castFunction;\n  } else if (typeof this.constructor.cast === 'function') {\n    castBigInt = this.constructor.cast();\n  } else {\n    castBigInt = SchemaBigInt.cast();\n  }\n\n  try {\n    return castBigInt(value);\n  } catch (error) {\n    throw new CastError('BigInt', 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};\n\n/**\n * Contains the handlers for different query operators for this schema type.\n * For example, `$conditionalHandlers.$in` is the function Mongoose calls to cast `$in` filter operators.","sourceCodeStart":155,"sourceCodeEnd":191,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/schema/bigint.js#L155-L191","documentation":"SchemaBigInt.cast delegates to the path's custom caster (_castFunction) or SchemaBigInt.cast(), which runs the value through BigInt(); anything BigInt() rejects (fractional numbers, non-numeric strings, symbols) is rethrown as CastError BigInt naming the path.","triggerScenarios":"`doc.big = 1.5` or `'1.5'`; `doc.big = '12px'`; JSON-parsed fractional numbers assigned to a BigInt path; float arithmetic results that already lost integer precision.","commonSituations":"JSON APIs (JSON cannot carry BigInt natively, and decimals arrive as Number); monetary values computed as floats then assigned to BigInt paths; string inputs never regex-checked for integer form.","solutions":["Validate and convert explicitly: require integer-compatible input, then assign BigInt(value); use 1n literals in code.","Reject decimal strings with /^-?\\d+$/ before assignment, or round intentionally then convert.","Install a lenient global caster if decimals must be accepted: mongoose.Schema.Types.BigInt.cast(v => BigInt(Math.round(Number(v))))."],"exampleFix":"// before\ndoc.amount = req.body.amount; // '19.99' -> CastError BigInt\n\n// after\nconst raw = String(req.body.amount);\nif (!/^-?\\d+$/.test(raw)) throw new Error('amount must be an integer string');\ndoc.amount = BigInt(raw);","handlingStrategy":"validation","validationCode":"const toBigInt = (v) => {\n  if (typeof v === 'bigint') return v;\n  const s = typeof v === 'string' || typeof v === 'number' ? String(v) : null;\n  if (s == null || !/^-?\\d+$/.test(s)) throw new TypeError(`not bigint-safe: ${String(v)}`);\n  return BigInt(s);\n};\ndoc.amount = toBigInt(req.body.amount);","typeGuard":"const isBigIntLike = (v) => typeof v === 'bigint' || ((typeof v === 'string' || (typeof v === 'number' && Number.isInteger(v))) && /^-?\\d+$/.test(String(v)));","tryCatchPattern":"try {\n  doc.big = value;\n} catch (err) {\n  if (err instanceof mongoose.Error.CastError && err.kind === 'BigInt') {\n    doc.big = toBigInt(value); // or reject the request\n  } else throw err;\n}","preventionTips":["Convert at the JSON boundary: regex-check numeric strings before they reach models.","Never route float arithmetic into BigInt paths - integers only, or use Decimal128.","Add a global custom caster only if you consciously decide how to round decimals."],"tags":["cast-error","bigint","json","input-validation"],"backgroundTag":"mongoose-cast-error","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}