{"id":"982206892efff534","repo":"mongodb/node-mongodb-native","slug":"argument-operations-must-be-an-array-of-document","errorCode":null,"errorMessage":"Argument \"operations\" must be an array of documents","messagePattern":"Argument \"operations\" must be an array of documents","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/collection.ts","lineNumber":367,"sourceCode":"   * - `updateOne`\n   * - `updateMany`\n   * - `deleteOne`\n   * - `deleteMany`\n   *\n   * If documents passed in do not contain the **_id** field,\n   * one will be added to each of the documents missing it by the driver, mutating the document. This behavior\n   * can be overridden by setting the **forceServerObjectId** flag.\n   *\n   * @param operations - Bulk operations to perform\n   * @param options - Optional settings for the command\n   * @throws MongoDriverError if operations is not an array\n   */\n  async bulkWrite(\n    operations: ReadonlyArray<AnyBulkWriteOperation<TSchema>>,\n    options?: BulkWriteOptions\n  ): Promise<BulkWriteResult> {\n    if (!Array.isArray(operations)) {\n      throw new MongoInvalidArgumentError('Argument \"operations\" must be an array of documents');\n    }\n\n    options = resolveOptions(this, options ?? {});\n\n    // TODO(NODE-7071): remove once the client doesn't need to be connected to construct\n    // bulk operations\n    const isConnected = this.client.topology != null;\n    if (!isConnected) {\n      await autoConnect(this.client);\n    }\n\n    // Create the bulk operation\n    const bulk: BulkOperationBase =\n      options.ordered === false\n        ? this.initializeUnorderedBulkOp(options)\n        : this.initializeOrderedBulkOp(options);\n\n    // for each op go through and add to the bulk","sourceCodeStart":349,"sourceCodeEnd":385,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/collection.ts#L349-L385","documentation":"Thrown by Collection.bulkWrite() when the operations argument is not an Array. Each element must be one of the recognized bulk operation shapes (insertOne, updateOne, updateMany, replaceOne, deleteOne, deleteMany). This MongoInvalidArgumentError is raised before the bulk op is built or any connection is checked out.","triggerScenarios":"Passing a single operation object instead of an array; passing undefined; passing a generator or custom iterable that is not an Array; passing an array-like object ({length, 0, 1}) that fails Array.isArray.","commonSituations":"Building operations conditionally and forgetting to initialize the accumulator to []; spreading a possibly-undefined value; refactoring from a fluent bulk to bulkWrite without wrapping; JSON input parsed into an object rather than an array.","solutions":["Ensure the argument is always an array: ops = ops ?? []; at the call site.","Wrap a single operation: bulkWrite(Array.isArray(ops) ? ops : [ops]).","Guard with Array.isArray(ops) and throw a domain-specific error before calling.","Type the producer function's return as AnyBulkWriteOperation<T>[] to catch regressions."],"exampleFix":"// before\nconst ops = condition ? [{ updateOne: {...} }] : undefined;\nawait collection.bulkWrite(ops);\n// after\nconst ops = condition ? [{ updateOne: {...} }] : [];\nawait collection.bulkWrite(ops);","handlingStrategy":"type-guard","validationCode":"function asBulkOps<T>(ops: unknown): T[] {\n  if (!Array.isArray(ops)) {\n    throw new TypeError('bulkWrite requires an array of operations');\n  }\n  return ops as T[];\n}\nawait collection.bulkWrite(asBulkOps(operations));","typeGuard":"const isBulkOperationArray = (v: unknown): v is object[] =>\n  Array.isArray(v) && v.every(o => o != null && typeof o === 'object');","tryCatchPattern":"try {\n  await collection.bulkWrite(operations);\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /operations.*must be an array/.test(e.message)) {\n    throw new TypeError('Expected an array of bulk operations');\n  }\n  throw e;\n}","preventionTips":["Initialize operation accumulators to [].","Type dynamic builders as AnyBulkWriteOperation<TSchema>[].","Avoid conditional assignment that leaves undefined."],"tags":["validation","typescript","crud","bulk-write"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}