Automattic/mongoose · error · CastError

Cast to Buffer failed for value "${value}" (type ${valueType

Error message

Cast to Buffer failed for value "${value}" (type ${valueType}) at path "${path}"

What it means

When casting a value that looks like a BSON Binary, mongoose copies its bytes and subtype; a Binary whose sub_type is not a number means the object is malformed or comes from an incompatible BSON implementation, so it is rejected as CastError Buffer instead of producing a corrupt Buffer.

Source

Thrown at lib/schema/buffer.js:165

  if (SchemaType._isRef(this, value, doc, init)) {
    if (value?.isMongooseBuffer) {
      return value;
    }

    if (Buffer.isBuffer(value)) {
      if (!value?.isMongooseBuffer) {
        value = new MongooseBuffer(value, [this.path, doc]);
        if (this.options.subtype != null) {
          value._subtype = this.options.subtype;
        }
      }
      return value;
    }

    if (value instanceof Binary) {
      ret = new MongooseBuffer(value.value(true), [this.path, doc]);
      if (typeof value.sub_type !== 'number') {
        throw new CastError('Buffer', value, this.path, null, this);
      }
      ret._subtype = value.sub_type;
      return ret;
    }

    if (value == null || utils.isNonBuiltinObject(value)) {
      return this._castRef(value, doc, init, options);
    }
  }

  // documents
  if (value?._id) {
    value = value._id;
  }

  if (value?.isMongooseBuffer) {
    return value;
  }

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Pass Buffer, Uint8Array, or plain strings to Buffer paths - mongoose converts them itself.
  2. Deduplicate BSON: ensure a single bson/mongodb driver version (npm dedupe / resolutions) and a mongoose version compatible with it.
  3. If constructing Binary manually, use the driver BSON class so sub_type is a number: new mongodb.Binary(buf, 0).

Example fix

// before
const fake = { value: () => buf, sub_type: undefined };
doc.data = fake; // CastError Buffer

// after
doc.data = Buffer.from(buf); // or new mongodb.Binary(buf, mongodb.Binary.SUBTYPE_DEFAULT)
Defensive patterns

Strategy: validation

Validate before calling

const isSafeBufferInput = (v) =>
  v == null || Buffer.isBuffer(v) || v instanceof Uint8Array || typeof v === 'string';
// before assigning a Binary, force a native type:
doc.data = isSafeBufferInput(v) ? v : Buffer.from(v.value(true));

Prevention

When it happens

Trigger: Passing a hand-built Binary-like object ({ value() {...}, sub_type: undefined }); two different bson package copies so the value duck-types into the Binary branch with a mismatched shape; bson major upgrades renaming sub_type to subType while mongoose/driver versions lag.

Common situations: Duplicate bson versions from dependency drift (npm ls bson showing several); mixing MongoDB driver versions with an older mongoose; test doubles imitating BSON Binary.

Related errors


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