{"record":{"id":"46de81320bf6bba4","repo":"mongodb/node-mongodb-native","slug":"document-toobject-bsonoptions-server-error-do","errorCode":null,"errorMessage":"${document.toObject(bsonOptions)} (server error document)","messagePattern":"(.+?) \\(server error document\\)","errorType":"exception","errorClass":"MongoServerError","httpStatus":null,"severity":"error","filePath":"src/cmap/connection.ts","lineNumber":563,"sourceCode":"      this.throwIfAborted();\n      for await (document of this.sendWire(message, options, responseType)) {\n        object = undefined;\n        if (options.session != null) {\n          updateSessionFromResponse(options.session, document);\n        }\n\n        if (document.$clusterTime) {\n          this.clusterTime = document.$clusterTime;\n          this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);\n        }\n\n        if (document.ok === 0) {\n          if (options.timeoutContext?.csotEnabled() && document.isMaxTimeExpiredError) {\n            throw new MongoOperationTimeoutError('Server reported a timeout error', {\n              cause: new MongoServerError((object ??= document.toObject(bsonOptions)))\n            });\n          }\n          throw new MongoServerError((object ??= document.toObject(bsonOptions)));\n        }\n\n        if (this.shouldEmitAndLogCommand) {\n          this.emitAndLogCommand(\n            this.monitorCommands,\n            Connection.COMMAND_SUCCEEDED,\n            message.databaseName,\n            this.established,\n            new CommandSucceededEvent(\n              this,\n              message,\n              message.moreToCome ? { ok: 1 } : (object ??= document.toObject(bsonOptions)),\n              started,\n              this.description.serverConnectionId\n            )\n          );\n        }\n","sourceCodeStart":545,"sourceCodeEnd":581,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/cmap/connection.ts#L545-L581","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Inspect error.code and error.codeName to identify the specific server error (e.g., 11000 = duplicate key).","Fix the application logic or schema that produced the invalid command.","Add the missing index, permission, or configuration the server complains about.","Handle known error codes with dedicated catch branches."],"exampleFix":"// before\nawait coll.insertOne({ _id: 1 }); // throws if _id:1 exists\n\n// after\ntry {\n  await coll.insertOne({ _id: 1 });\n} catch (e) {\n  if (e.code === 11000) { /* duplicate key */ }\n}","handlingStrategy":"try-catch","validationCode":null,"typeGuard":"function isDuplicateKey(e: unknown): boolean {\n  return (e as any)?.code === 11000;\n}","tryCatchPattern":"try {\n  await coll.insertOne(doc);\n} catch (e) {\n  if ((e as any)?.code === 11000) { /* handle duplicate key */ }\n  else throw e;\n}","preventionTips":["Inspect error.code to branch on specific server errors.","Validate uniqueness/index constraints before writes when feasible.","Use ordered:false and inspect writeErrors for bulk operations."],"tags":["server-error","write-errors","duplicate-key","validation"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}