{"record":{"id":"37c4171571dd0e72","repo":"mongodb/node-mongodb-native","slug":"could-not-serialize-ns-info-to-bson","errorCode":null,"errorMessage":"Could not serialize ns info to BSON","messagePattern":"Could not serialize ns info to BSON","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/operations/client_bulk_write/command_builder.ts","lineNumber":174,"sourceCode":"        }\n      } else {\n        // The namespace is not already in the nsInfo so we will set it in the map, and\n        // construct our nsInfo and ops documents and buffers.\n        namespaces.set(ns, currentNamespaceIndex);\n        const nsInfo = { ns: ns };\n        const operation = buildOperation(\n          model,\n          currentNamespaceIndex,\n          this.pkFactory,\n          this.options\n        );\n        let nsInfoBuffer;\n        let operationBuffer;\n        try {\n          nsInfoBuffer = BSON.serialize(nsInfo);\n          operationBuffer = BSON.serialize(operation);\n        } catch (cause) {\n          throw new MongoInvalidArgumentError(`Could not serialize ns info to BSON`, { cause });\n        }\n\n        validateBufferSize('nsInfo', nsInfoBuffer, maxBsonObjectSize);\n        validateBufferSize('ops', operationBuffer, maxBsonObjectSize);\n\n        // Check if the operation and nsInfo buffers can fit in the command. If they\n        // can, then add the operation and nsInfo to their respective document\n        // sequences and increment the current length as long as the ops don't exceed\n        // the maxWriteBatchSize.\n        if (\n          commandLength + nsInfoBuffer.length + operationBuffer.length < maxMessageSizeBytes &&\n          command.ops.documents.length < maxWriteBatchSize\n        ) {\n          // Pushing to the ops document sequence returns the total byte length of the document sequence.\n          commandLength =\n            MESSAGE_OVERHEAD_BYTES +\n            command.nsInfo.push(nsInfo, nsInfoBuffer) +\n            command.ops.push(operation, operationBuffer);","sourceCodeStart":156,"sourceCodeEnd":192,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/operations/client_bulk_write/command_builder.ts#L156-L192","documentation":"Companion to the operation serialization error, thrown when BSON cannot serialize the namespace-info document ({ ns: model.namespace }) for a client bulk write batch. Because ns is normally just a string, this error almost always indicates that the namespace string itself is malformed in a way BSON rejects (e.g. contains a NUL byte or invalid UTF-8).","triggerScenarios":"Passing a namespace that contains binary/NUL characters or otherwise invalid UTF-8 sequences in any ClientBulkWriteModel.namespace field.","commonSituations":"Constructing namespace strings dynamically from untrusted input that includes control characters; copying a buffer into a string accidentally; rare driver-internal corruption.","solutions":["Inspect error.cause for the precise serialization failure.","Sanitize the namespace string: ensure it matches /^[^.\\\\/]*\\\\.[^.\\\\/]*$/ and contains only printable characters.","Build namespaces from known database + collection names rather than concatenating raw user input."],"exampleFix":"// before\nawait client.bulkWrite([{\n  insertOne: { namespace: 'db\\\\0coll', document: { a: 1 } } // contains NUL byte\n}]);\n\n// after\nawait client.bulkWrite([{\n  insertOne: { namespace: 'db.coll', document: { a: 1 } }\n}]);","handlingStrategy":"validation","validationCode":"const NS_RE = /^[^.\\/$]*\\.[^.\\/$]*$/;\nif (!NS_RE.test(namespace) || /[\\x00-\\x1f]/.test(namespace)) {\n  throw new Error(`Invalid namespace: ${JSON.stringify(namespace)}`);\n}","typeGuard":"const isValidNamespace = (v: unknown): v is string =>\n  typeof v === 'string' && /^[^.\\/$]*\\.[^.\\/$]*$/.test(v) && ![...v].some(c => c.charCodeAt(0) < 32);","tryCatchPattern":null,"preventionTips":["Build namespaces from validated database and collection names, never raw user input.","Sanitize control characters before constructing models."],"tags":["bulk-write","bson","namespace"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}