{"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/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/operations/client_bulk_write/command_builder.ts#L156-L192","documentation":"Thrown while building a client bulk write command when BSON.serialize() fails on an nsInfo entry ({ ns: <namespace string > }). The original error is attached as `cause`. Because nsInfo only holds the namespace string, a failure here almost always means the namespace string itself is malformed or contains an unserializable (non-string) type.","triggerScenarios":"A model.namespace that is undefined, null, an object, or a string with embedded non-BSON characters; constructing models dynamically and leaving namespace unset.","commonSituations":"Missing namespace field in a programmatic model; building namespace from undefined variables (resulting in 'undefined'); feeding non-string values from config.","solutions":["Ensure every model.namespace is a non-empty 'database.collection' string.","Validate that namespace variables are defined and are strings before constructing models.","Inspect err.cause for the exact BSON encoding failure and trace which model produced it."],"exampleFix":"// before\nawait client.bulkWrite([{\n  namespace: undefined, // throws nsInfo serialization\n  name: 'insertOne',\n  document: { a: 1 }\n}]);\n\n// after\nawait client.bulkWrite([{\n  namespace: 'mydb.mycoll',\n  name: 'insertOne',\n  document: { a: 1 }\n}]);","handlingStrategy":"validation","validationCode":"function validNs(ns) {\n  return typeof ns === 'string' && /^[^.]+\\.[^.]+$/.test(ns);\n}\nmodels.forEach(m => { if (!validNs(m.namespace)) throw new Error('Bad namespace'); });","typeGuard":"function isNamespaceString(v): v is string { return typeof v === 'string' && v.includes('.'); }","tryCatchPattern":"try { await client.bulkWrite(models); } catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /ns info/.test(e.message)) {\n    console.error('nsInfo serialization failed:', e.cause);\n  }\n  throw e;\n}","preventionTips":["Always set model.namespace as 'db.collection'","Validate namespace is a non-empty string","Inspect err.cause to locate the bad model"],"tags":["bulk-write","bson","serialization","namespace","client-bulk-write"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}