{"record":{"id":"9af07443fe8c8b8e","repo":"Automattic/mongoose","slug":"can-t-use-conditional-with-buffer","errorCode":null,"errorMessage":"Can't use ${$conditional} with Buffer.","messagePattern":"Can't use (.+?) with Buffer\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"lib/schema/buffer.js","lineNumber":304,"sourceCode":"  enumerable: false,\n  value: $conditionalHandlers\n});\n\n\n/**\n * Casts contents for queries.\n *\n * @param {string} $conditional\n * @param {any} [value]\n * @api private\n */\n\nSchemaBuffer.prototype.castForQuery = function($conditional, val, context) {\n  let handler;\n  if ($conditional != null) {\n    handler = this.$conditionalHandlers[$conditional];\n    if (!handler) {\n      throw new Error('Can\\'t use ' + $conditional + ' with Buffer.');\n    }\n    return handler.call(this, val);\n  }\n\n  let casted;\n  try {\n    casted = this.applySetters(val, context);\n  } catch (err) {\n    if (err instanceof CastError && err.path === this.path && this.$fullPath != null) {\n      err.path = this.$fullPath;\n    }\n    throw err;\n  }\n  return casted ? casted.toObject({ transform: false, virtuals: false }) : casted;\n};\n\n/**\n * Returns this schema type's representation in a JSON schema.","sourceCodeStart":286,"sourceCodeEnd":322,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/schema/buffer.js#L286-L322","documentation":"SchemaBuffer.castForQuery throws a plain Error when a query filter applies an operator that has no registered handler for Buffer paths. Buffer's handler set is the base SchemaType handlers ($in, $nin, $ne, $eq, $exists, ...) plus $gt/$gte/$lt/$lte and the bitwise operators $bitsAllSet/$bitsAnySet/$bitsAllClear/$bitsAnyClear. Any other operator in a filter object for a Buffer path — e.g. $regex, $mod, $all — reaches the guard.","triggerScenarios":"`Model.find({ dataHash: { $regex: /^abc/ } })` or any filter `{ <bufferPath>: { $<op>: value } }` where $op is not in SchemaBuffer's $conditionalHandlers. Also `Model.find({ buf: { $near: [1, 2] } })` or operator typos like `$regexi`.","commonSituations":"Reusing a query originally written for a String path against a Buffer path after a schema change; dynamic query builders (search filters, GraphQL resolvers) that apply the same operator set to every field; using text-ish operators on binary hashes.","solutions":["Change the schema so the value you search with text operators is a String (store hex/base64 alongside) and index that field","Use operators Buffer supports: comparisons ($gt/$lt/...) and bitwise ($bitsAllSet/...); remember $in/$ne/$exists work from the base handlers","In dynamic query builders, whitelist operators per schema type before composing the filter","Catch the Error and surface which path/operator pair was rejected so callers can fix their query"],"exampleFix":"// before\nModel.find({ dataHash: { $regex: `^${prefix}` } }); // Buffer path\n\n// after\nModel.find({ dataHashHex: { $regex: `^${prefix}` } }); // keep a hex String copy of the hash","handlingStrategy":"validation","validationCode":"const BUFFER_OPS = new Set(['$gt','$gte','$lt','$lte','$in','$nin','$ne','$eq','$exists','$bitsAllSet','$bitsAnySet','$bitsAllClear','$bitsAnyClear','$not','$cmp','$and','$or']);\nfunction assertBufferOpsSafe(filter) {\n  for (const [k, v] of Object.entries(filter ?? {})) {\n    if (k.startsWith('$')) continue;\n    if (v && typeof v === 'object' && !Array.isArray(v)) {\n      for (const op of Object.keys(v)) {\n        if (op.startsWith('$') && !BUFFER_OPS.has(op)) throw new Error(`operator ${op} not allowed on ${k}`);\n      }\n    }\n  }\n}","typeGuard":null,"tryCatchPattern":"try { await Model.find(filter); } catch (err) { if (/Can't use .* with Buffer/.test(err.message)) { throw Object.assign(new Error('unsupported buffer operator'), { status: 400 }); } throw err; }","preventionTips":["Keep a per-type operator whitelist in dynamic query builders","Store searchable encodings (hex/base64) in String paths for text operators","Add integration tests for every operator your API exposes"],"tags":["mongoose","buffer","query","operator","filter"],"backgroundTag":"unsupported-query-operator","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}