mongodb/node-mongodb-native · error · MongoBulkWriteError

write operation failed

Error message

write operation failed

What it means

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.

Source

Thrown at src/bulk/common.ts:1237

      return await this.collection.client.withSession({ explicit: false }, async session => {
        return await executeCommands(this, { ...finalOptions, session });
      });
    }

    return await executeCommands(this, { ...finalOptions });
  }

  /**
   * Handles the write error before executing commands
   * @internal
   */
  handleWriteError(writeResult: BulkWriteResult): void {
    if (this.s.bulkResult.writeErrors.length > 0) {
      const msg = this.s.bulkResult.writeErrors[0].errmsg
        ? this.s.bulkResult.writeErrors[0].errmsg
        : 'write operation failed';

      throw new MongoBulkWriteError(
        {
          message: msg,
          code: this.s.bulkResult.writeErrors[0].code,
          writeErrors: this.s.bulkResult.writeErrors
        },
        writeResult
      );
    }

    const writeConcernError = writeResult.getWriteConcernError();
    if (writeConcernError) {
      throw new MongoBulkWriteError(writeConcernError, writeResult);
    }
  }

  abstract addToOperationsList(
    batchType: BatchType,
    document: Document | UpdateStatement | DeleteStatement

View on GitHub (pinned to dce7939f86)

Solutions

  1. 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.
  2. Match on err.code (e.g. 11000 for duplicate key) to handle specific server-side causes.
  3. For unique-key conflicts, deduplicate input or use upsert; for validation failures, fix the document to satisfy the $jsonSchema validator.
  4. If write-concern related, check err.result.getWriteConcernError() and the replica set health/timeout settings.

Example fix

// before
try {
  await coll.bulkWrite(ops);
} catch (e) {
  console.error(e.message); // 'write operation failed' — unhelpful
}

// after
try {
  await coll.bulkWrite(ops);
} catch (e) {
  const we = e.result?.writeErrors ?? [];
  for (const w of we) {
    console.error(`op#${w.index} code=${w.code}: ${w.errmsg}`);
  }
}
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-validate to avoid common server-side write errors.
// (Cannot prevent all server errors, but can catch the frequent ones.)

function normalizeOps(ops: AnyBulkWriteOperation[]) {
  // ensure update bodies have atomic ops, replace bodies do not, filters are present
  return ops.map(op => {
    if ('updateOne' in op && op.updateOne && !hasAtomicOps(op.updateOne.update)) {
      return { updateOne: { ...op.updateOne, update: { $set: op.updateOne.update } } };
    }
    return op;
  });
}

await coll.bulkWrite(normalizeOps(ops));

Type guard

import { MongoBulkWriteError } from 'mongodb';

function isMongoBulkWriteError(e: unknown): e is MongoBulkWriteError & { result: { writeErrors: any[]; getWriteConcernError?: () => any } } {
  return e instanceof Error && (e as any).name === 'MongoBulkWriteError' && !!(e as any).result;
}

Try / catch

try {
  await coll.bulkWrite(ops);
} catch (e) {
  if (!(e instanceof MongoBulkWriteError)) throw e;
  for (const we of e.result?.writeErrors ?? []) {
    console.error(`op#${we.index} code=${we.code}: ${we.errmsg}`);
    if (we.code === 11000) {
      // duplicate key — dedupe input or switch to upsert
    }
  }
  const wc = e.result?.getWriteConcernError?.();
  if (wc) console.error('write-concern error:', wc);
}

Prevention

When it happens

Trigger: 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'`).

Common situations: 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.

Related errors


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