mongodb/node-mongodb-native · error · MongoInvalidArgumentError
Could not serialize ns info to BSON
Error message
Could not serialize ns info to BSON
What it means
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.
Source
Thrown at src/operations/client_bulk_write/command_builder.ts:174
}
} else {
// The namespace is not already in the nsInfo so we will set it in the map, and
// construct our nsInfo and ops documents and buffers.
namespaces.set(ns, currentNamespaceIndex);
const nsInfo = { ns: ns };
const operation = buildOperation(
model,
currentNamespaceIndex,
this.pkFactory,
this.options
);
let nsInfoBuffer;
let operationBuffer;
try {
nsInfoBuffer = BSON.serialize(nsInfo);
operationBuffer = BSON.serialize(operation);
} catch (cause) {
throw new MongoInvalidArgumentError(`Could not serialize ns info to BSON`, { cause });
}
validateBufferSize('nsInfo', nsInfoBuffer, maxBsonObjectSize);
validateBufferSize('ops', operationBuffer, maxBsonObjectSize);
// Check if the operation and nsInfo buffers can fit in the command. If they
// can, then add the operation and nsInfo to their respective document
// sequences and increment the current length as long as the ops don't exceed
// the maxWriteBatchSize.
if (
commandLength + nsInfoBuffer.length + operationBuffer.length < maxMessageSizeBytes &&
command.ops.documents.length < maxWriteBatchSize
) {
// Pushing to the ops document sequence returns the total byte length of the document sequence.
commandLength =
MESSAGE_OVERHEAD_BYTES +
command.nsInfo.push(nsInfo, nsInfoBuffer) +
command.ops.push(operation, operationBuffer);View on GitHub (pinned to 3366c21a63)
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.
Example fix
// before
await client.bulkWrite([{
namespace: undefined, // throws nsInfo serialization
name: 'insertOne',
document: { a: 1 }
}]);
// after
await client.bulkWrite([{
namespace: 'mydb.mycoll',
name: 'insertOne',
document: { a: 1 }
}]); Defensive patterns
Strategy: validation
Validate before calling
function validNs(ns) {
return typeof ns === 'string' && /^[^.]+\.[^.]+$/.test(ns);
}
models.forEach(m => { if (!validNs(m.namespace)) throw new Error('Bad namespace'); }); Type guard
function isNamespaceString(v): v is string { return typeof v === 'string' && v.includes('.'); } Try / catch
try { await client.bulkWrite(models); } catch (e) {
if (e instanceof MongoInvalidArgumentError && /ns info/.test(e.message)) {
console.error('nsInfo serialization failed:', e.cause);
}
throw e;
} Prevention
- Always set model.namespace as 'db.collection'
- Validate namespace is a non-empty string
- Inspect err.cause to locate the bad model
When it happens
Trigger: A model.namespace that is undefined, null, an object, or a string with embedded non-BSON characters; constructing models dynamically and leaving namespace unset.
Common situations: Missing namespace field in a programmatic model; building namespace from undefined variables (resulting in 'undefined'); feeding non-string values from config.
Related errors
- Could not serialize operation to BSON
- Document is larger than the maximum size ${this.s.maxBsonObj
- Document is larger than the maximum size ${this.s.maxBsonObj
- Client bulk write operation ${name} of length ${buffer.lengt
- Client bulk write update models must only contain atomic mod
AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04).
Data as JSON: /data/errors/37c4171571dd0e72.json.
Report an issue: GitHub.