{"id":"dd4b43c51035430a","repo":"mongodb/node-mongodb-native","slug":"dynamic-server-error-response-propagated-via-mon","errorCode":null,"errorMessage":"<dynamic: server error response propagated via MongoServerError(res)>","messagePattern":"<dynamic: server error response propagated via MongoServerError\\(res\\)>","errorType":"exception","errorClass":"MongoServerError","httpStatus":null,"severity":"error","filePath":"src/operations/delete.ts","lineNumber":116,"sourceCode":"\n    return command;\n  }\n}\n\nexport class DeleteOneOperation extends DeleteOperation {\n  constructor(ns: MongoDBCollectionNamespace, filter: Document, options: DeleteOptions) {\n    super(ns, [makeDeleteStatement(filter, { ...options, limit: 1 })], options);\n  }\n\n  override handleOk(\n    response: InstanceType<typeof this.SERVER_COMMAND_RESPONSE_TYPE>\n  ): DeleteResult {\n    const res = super.handleOk(response);\n\n    // @ts-expect-error Explain commands have broken TS\n    if (this.explain) return res;\n\n    if (res.code) throw new MongoServerError(res);\n    if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]);\n\n    return {\n      acknowledged: this.writeConcern?.w !== 0,\n      deletedCount: res.n\n    };\n  }\n}\nexport class DeleteManyOperation extends DeleteOperation {\n  constructor(ns: MongoDBCollectionNamespace, filter: Document, options: DeleteOptions) {\n    super(ns, [makeDeleteStatement(filter, options)], options);\n  }\n\n  override handleOk(\n    response: InstanceType<typeof this.SERVER_COMMAND_RESPONSE_TYPE>\n  ): DeleteResult {\n    const res = super.handleOk(response);\n","sourceCodeStart":98,"sourceCodeEnd":134,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/operations/delete.ts#L98-L134","documentation":"After a deleteOne command completes, the driver inspects the server response in DeleteOneOperation.handleOk (src/operations/delete.ts:116). If the response carries a top-level error code, the entire response document is wrapped in a MongoServerError and thrown. This surfaces command-level failures such as write-concern timeouts, authorization failures, or namespace errors that the server reports at the command level rather than per-document.","triggerScenarios":"Calling collection.deleteOne(filter) and the server returns a response object whose `code` field is set — e.g. writeConcern timeout (code 64), Unauthorized (code 13), or a failed retryable-write commitment after a failover.","commonSituations":"Write concern `wtimeout` exceeded on a replica set, insufficient permissions for the authenticated user, sharded cluster shard-key errors, or a failover where the original primary could not replicate the write before reporting back.","solutions":["Inspect err.code and err.codeName on the caught MongoServerError to determine the server-side cause; the message is server-generated and dynamic.","If err.code is 64 (WriteConcernFailed / wtimeout), verify replica set health and the secondary lag, then retry or lower the write concern.","If err.code is 13 (Unauthorized), check the authenticated user's roles and permissions on the target namespace.","Add retry logic only for transient codes using the RetryableError label (err.hasErrorLabel('RetryableError'))."],"exampleFix":"// before\nconst result = await collection.deleteOne({ _id });\nconsole.log(result.deletedCount);\n\n// after\ntry {\n  const result = await collection.deleteOne({ _id });\n  console.log(result.deletedCount);\n} catch (err) {\n  if (err instanceof MongoServerError) {\n    console.error(`server error ${err.code}: ${err.message}`);\n    if (err.code === 64) {\n      // write concern timeout — check replica set health\n    }\n  }\n  throw err;\n}","handlingStrategy":"try-catch","validationCode":"// Validate write concern and permissions before deleteOne is impractical client-side;\n// instead ensure the client has adequate privileges and a healthy write concern:\nif (collection.writeConcern?.w === 0) {\n  // unacknowledged — server errors will not propagate; switch to acknowledged\n}","typeGuard":null,"tryCatchPattern":"try {\n  await collection.deleteOne(filter);\n} catch (err) {\n  if (err instanceof MongoServerError) {\n    // err.code and err.message are server-supplied\n    switch (err.code) {\n      case 64: /* WriteConcernFailed */ break;\n      case 13: /* Unauthorized */ break;\n      default: throw err;\n    }\n  } else throw err;\n}","preventionTips":["Use an acknowledged write concern (w >= 1) so server errors are reported.","Ensure the authenticated user has remove privileges on the namespace.","Monitor replica set health to avoid write-concern timeouts."],"tags":["server-error","delete","write-concern","retryable"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}