Automattic/mongoose · error · Error

Cannot convert value to BigInt: "${val}"

Error message

Cannot convert value to BigInt: "${val}"

What it means

castBigInt accepts null and '' (both become null), bigint, BSON Long, and string/number via BigInt(); every other type reaches the final throw with the value interpolated into the message. Arrays, plain objects, booleans, and exotic instances therefore cannot populate a BigInt path without explicit conversion.

Source

Thrown at lib/cast/bigint.js:45

    if (val > MAX_BIGINT || val < MIN_BIGINT) {
      throw new Error(ERROR_MESSAGE);
    }
    return val;
  }

  if (val instanceof Long) {
    return val.toBigInt();
  }

  if (typeof val === 'string' || typeof val === 'number') {
    val = BigInt(val);
    if (val > MAX_BIGINT || val < MIN_BIGINT) {
      throw new Error(ERROR_MESSAGE);
    }
    return val;
  }

  throw new Error(`Cannot convert value to BigInt: "${val}"`);
};

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Pass a supported type: bigint, numeric string, number, or BSON Long from the mongodb/bson package
  2. Extract the primitive before assignment: doc.big = raw.value
  3. Add a custom setter on the path if wrapped types must be accepted

Example fix

// before
doc.big = { value: '123' };

// after
doc.big = '123'; // or 123n, or new Long(123)
Defensive patterns

Strategy: type-guard

Validate before calling

const { Long } = require('mongodb');
function isBigIntCastable(v) {
  return v == null || v === '' ||
    typeof v === 'bigint' || typeof v === 'string' ||
    typeof v === 'number' || v instanceof Long;
}
if (!isBigIntCastable(input)) {
  throw new TypeError(`Not castable to BigInt: ${typeof input}`);
}

Type guard

const { Long } = require('mongodb');
function isBigIntCastable(v) {
  return v == null || v === '' ||
    typeof v === 'bigint' || typeof v === 'string' ||
    typeof v === 'number' || v instanceof Long;
}

Try / catch

try {
  doc.big = raw;
  await doc.save();
} catch (err) {
  if (err.message.startsWith('Cannot convert value to BigInt')) {
    // the message shows the exact value; convert it explicitly and re-save
  }
  throw err;
}

Prevention

When it happens

Trigger: doc.big = { value: '123' }; doc.big = [123n]; doc.big = true; assigning a custom class instance or a Date to a BigInt path.

Common situations: Deserialized JSON objects assigned where a scalar was expected; wrapper types from form/ORM layers; passing ObjectId or Date by mistake; config parsed into structured values.

Related errors


AI-assisted analysis of Automattic/mongoose@49cdab0136 (2026-08-21). Data as JSON: /api/errors/871f7ab927c763e7. Report an issue: GitHub.