{"record":{"id":"58c0bccdb24ae522","repo":"mongodb/node-mongodb-native","slug":"write-operation-failed","errorCode":null,"errorMessage":"write operation failed","messagePattern":"write operation failed","errorType":"exception","errorClass":"MongoBulkWriteError","httpStatus":null,"severity":"error","filePath":"src/bulk/common.ts","lineNumber":1237,"sourceCode":"      return await this.collection.client.withSession({ explicit: false }, async session => {\n        return await executeCommands(this, { ...finalOptions, session });\n      });\n    }\n\n    return await executeCommands(this, { ...finalOptions });\n  }\n\n  /**\n   * Handles the write error before executing commands\n   * @internal\n   */\n  handleWriteError(writeResult: BulkWriteResult): void {\n    if (this.s.bulkResult.writeErrors.length > 0) {\n      const msg = this.s.bulkResult.writeErrors[0].errmsg\n        ? this.s.bulkResult.writeErrors[0].errmsg\n        : 'write operation failed';\n\n      throw new MongoBulkWriteError(\n        {\n          message: msg,\n          code: this.s.bulkResult.writeErrors[0].code,\n          writeErrors: this.s.bulkResult.writeErrors\n        },\n        writeResult\n      );\n    }\n\n    const writeConcernError = writeResult.getWriteConcernError();\n    if (writeConcernError) {\n      throw new MongoBulkWriteError(writeConcernError, writeResult);\n    }\n  }\n\n  abstract addToOperationsList(\n    batchType: BatchType,\n    document: Document | UpdateStatement | DeleteStatement","sourceCodeStart":1219,"sourceCodeEnd":1255,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/bulk/common.ts#L1219-L1255","documentation":"Thrown as MongoBulkWriteError by BulkOperationBase.handleWriteError() (src/bulk/common.ts:1237) as a fallback message when a write produced write errors but the first error's `errmsg` field was empty/missing. The driver wraps the server's per-write errors into a single MongoBulkWriteError; this string is only used when the server gave no usable message, so the real detail is in result.writeErrors (code + index) rather than the top-level message.","triggerScenarios":"A bulk write where the server reported one or more writeErrors (e.g. duplicate key, validation failure, write-concern failure on a secondary) and the first error lacked an errmsg. The fallback is selected at src/bulk/common.ts:1233-1235 (`const msg = ... ? ... : 'write operation failed'`).","commonSituations":"Duplicate-key (E11000) on an insert, schema/validation rule violations, index conflicts, unique-constraint failures during upserts, or write-concern errors. The generic message shows up on older servers or edge cases where errmsg is absent; inspect err.result.writeErrors for the real cause.","solutions":["Inspect the error's result.writeErrors array: each entry has index, code, errmsg, and errInfo — the per-op detail is there even when the top-level message is generic.","Match on err.code (e.g. 11000 for duplicate key) to handle specific server-side causes.","For unique-key conflicts, deduplicate input or use upsert; for validation failures, fix the document to satisfy the $jsonSchema validator.","If write-concern related, check err.result.getWriteConcernError() and the replica set health/timeout settings."],"exampleFix":"// before\ntry {\n  await coll.bulkWrite(ops);\n} catch (e) {\n  console.error(e.message); // 'write operation failed' — unhelpful\n}\n\n// after\ntry {\n  await coll.bulkWrite(ops);\n} catch (e) {\n  const we = e.result?.writeErrors ?? [];\n  for (const w of we) {\n    console.error(`op#${w.index} code=${w.code}: ${w.errmsg}`);\n  }\n}","handlingStrategy":"try-catch","validationCode":"// Pre-validate to avoid common server-side write errors.\n// (Cannot prevent all server errors, but can catch the frequent ones.)\n\nfunction normalizeOps(ops: AnyBulkWriteOperation[]) {\n  // ensure update bodies have atomic ops, replace bodies do not, filters are present\n  return ops.map(op => {\n    if ('updateOne' in op && op.updateOne && !hasAtomicOps(op.updateOne.update)) {\n      return { updateOne: { ...op.updateOne, update: { $set: op.updateOne.update } } };\n    }\n    return op;\n  });\n}\n\nawait coll.bulkWrite(normalizeOps(ops));","typeGuard":"import { MongoBulkWriteError } from 'mongodb';\n\nfunction isMongoBulkWriteError(e: unknown): e is MongoBulkWriteError & { result: { writeErrors: any[]; getWriteConcernError?: () => any } } {\n  return e instanceof Error && (e as any).name === 'MongoBulkWriteError' && !!(e as any).result;\n}","tryCatchPattern":"try {\n  await coll.bulkWrite(ops);\n} catch (e) {\n  if (!(e instanceof MongoBulkWriteError)) throw e;\n  for (const we of e.result?.writeErrors ?? []) {\n    console.error(`op#${we.index} code=${we.code}: ${we.errmsg}`);\n    if (we.code === 11000) {\n      // duplicate key — dedupe input or switch to upsert\n    }\n  }\n  const wc = e.result?.getWriteConcernError?.();\n  if (wc) console.error('write-concern error:', wc);\n}","preventionTips":["Always inspect err.result.writeErrors (index/code/errmsg) rather than relying on the top-level message.","Match on err.code for known server errors (e.g. 11000 duplicate key, 121 validator failure).","Deduplicate insert inputs or use upsert:true to avoid E11000 in bulk.","For write-concern errors, verify replica set health and wtimeout/timeoutMS settings.","Confirm collection $jsonSchema validators accept your documents before bulk inserts."],"tags":["bulk-write","server-error","write-errors","write-concern"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}