Automattic/mongoose · error · CastError

Cast to boolean failed for value "${value}" at path "${path}

Error message

Cast to boolean failed for value "${value}" at path "${path}"

What it means

castBoolean accepts exactly the values in two Sets -- true/'true'/1/'1'/'yes' map to true and false/'false'/0/'0'/'no' map to false -- while null/undefined pass through. Anything else throws CastError('boolean', value, path); the sets are case-sensitive, so 'TRUE', 'Yes', 'y', and 'on' all fail.

Source

Thrown at lib/cast/boolean.js:28

 * @param {string} [path] optional the path to set on the CastError
 * @return {boolean|null|undefined}
 * @throws {CastError} if `value` is not one of the allowed values
 * @api private
 */

module.exports = function castBoolean(value, path) {
  if (module.exports.convertToTrue.has(value)) {
    return true;
  }
  if (module.exports.convertToFalse.has(value)) {
    return false;
  }

  if (value == null) {
    return value;
  }

  throw new CastError('boolean', value, path);
};

module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']);
module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']);

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Normalize to a real boolean yourself: doc.active = req.body.active === 'on'
  2. Restrict string inputs to the exact vocabulary: 'true'/'false'/'1'/'0'/'yes'/'no'
  3. Extend the vocabulary once, app-wide: const castBoolean = require('mongoose/lib/cast/boolean'); castBoolean.convertToTrue.add('y'); castBoolean.convertToFalse.add('n');

Example fix

// before
doc.active = 'on'; // not in convertToTrue / convertToFalse

// after
doc.active = req.body.active === 'on';
Defensive patterns

Strategy: validation

Validate before calling

const castBoolean = require('mongoose/lib/cast/boolean');
function isCastableBoolean(v) {
  return v == null ||
    castBoolean.convertToTrue.has(v) ||
    castBoolean.convertToFalse.has(v);
}
if (!isCastableBoolean(req.body.active)) {
  throw new TypeError('Invalid boolean input');
}

Type guard

const castBoolean = require('mongoose/lib/cast/boolean');
function isCastableBoolean(v) {
  return v == null ||
    castBoolean.convertToTrue.has(v) ||
    castBoolean.convertToFalse.has(v);
}

Try / catch

try {
  await doc.save();
} catch (err) {
  if (err.name === 'CastError' && err.kind === 'boolean') {
    // err.value shows the offending input; map it to true/false and retry
  }
  throw err;
}

Prevention

When it happens

Trigger: doc.flag = 'y' | 'on' | 2 | 'TRUE'; casting req.query.active ('on' from a checkbox) straight into a Boolean path; Model.find({ active: 'On' }).

Common situations: HTML checkboxes that submit 'on'; YAML/env values like 'Yes'/'Off'; free-text boolean fields; case mismatches between client and server conventions; numeric flags other than 0/1.

Related errors


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