mongodb/node-mongodb-native · error · MongoServerError

${document.toObject(bsonOptions)} (server error document)

Error message

${document.toObject(bsonOptions)} (server error document)

What it means

A generic MongoServerError constructed from the raw server response document when document.ok === 0 but the response is NOT a CSOT maxTimeMS error (or CSOT is not enabled). This is the default server-error path: the entire BSON reply becomes the error object, so its code, codeName, errmsg, and writeErrors are surfaced to the caller. The message is derived from the serialized server document.

Source

Thrown at src/cmap/connection.ts:563

      this.throwIfAborted();
      for await (document of this.sendWire(message, options, responseType)) {
        object = undefined;
        if (options.session != null) {
          updateSessionFromResponse(options.session, document);
        }

        if (document.$clusterTime) {
          this.clusterTime = document.$clusterTime;
          this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);
        }

        if (document.ok === 0) {
          if (options.timeoutContext?.csotEnabled() && document.isMaxTimeExpiredError) {
            throw new MongoOperationTimeoutError('Server reported a timeout error', {
              cause: new MongoServerError((object ??= document.toObject(bsonOptions)))
            });
          }
          throw new MongoServerError((object ??= document.toObject(bsonOptions)));
        }

        if (this.shouldEmitAndLogCommand) {
          this.emitAndLogCommand(
            this.monitorCommands,
            Connection.COMMAND_SUCCEEDED,
            message.databaseName,
            this.established,
            new CommandSucceededEvent(
              this,
              message,
              message.moreToCome ? { ok: 1 } : (object ??= document.toObject(bsonOptions)),
              started,
              this.description.serverConnectionId
            )
          );
        }

View on GitHub (pinned to dce7939f86)

Solutions

  1. Inspect error.code and error.codeName to identify the specific server error (e.g., 11000 = duplicate key).
  2. Fix the application logic or schema that produced the invalid command.
  3. Add the missing index, permission, or configuration the server complains about.
  4. Handle known error codes with dedicated catch branches.

Example fix

// before
await coll.insertOne({ _id: 1 }); // throws if _id:1 exists

// after
try {
  await coll.insertOne({ _id: 1 });
} catch (e) {
  if (e.code === 11000) { /* duplicate key */ }
}
Defensive patterns

Strategy: try-catch

Type guard

function isDuplicateKey(e: unknown): boolean {
  return (e as any)?.code === 11000;
}

Try / catch

try {
  await coll.insertOne(doc);
} catch (e) {
  if ((e as any)?.code === 11000) { /* handle duplicate key */ }
  else throw e;
}

Prevention

When it happens

Trigger: Any command where the server replies with ok: 0 for a non-timeout reason — duplicate key, write validation failure, unauthorized, index options conflict, etc. This is the catch-all server-error throw in Connection.sendCommand.

Common situations: Inserting a duplicate _id; violating a unique index; auth/permission failures; malformed pipeline stages; server-side field-type validation; namespace conflicts. Essentially any normal MongoDB command error surfaces here.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@dce7939f86 (2026-08-11). Data as JSON: /api/errors/46de81320bf6bba4. Report an issue: GitHub.