{"record":{"id":"e0fb990ab93f3ccb","repo":"mongodb/node-mongodb-native","slug":"argument-docs-must-be-an-array-of-documents","errorCode":null,"errorMessage":"Argument \"docs\" must be an array of documents","messagePattern":"Argument \"docs\" must be an array of documents","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/collection.ts","lineNumber":317,"sourceCode":"        resolveOptions(this, options)\n      ) as TODO_NODE_3286\n    );\n  }\n\n  /**\n   * Inserts an array of documents into MongoDB. 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 docs - The documents to insert\n   * @param options - Optional settings for the command\n   */\n  async insertMany(\n    docs: ReadonlyArray<OptionalUnlessRequiredId<TSchema>>,\n    options?: BulkWriteOptions\n  ): Promise<InsertManyResult<TSchema>> {\n    if (!Array.isArray(docs)) {\n      throw new MongoInvalidArgumentError('Argument \"docs\" must be an array of documents');\n    }\n    options = resolveOptions(this, options ?? {});\n\n    const acknowledged = WriteConcern.fromOptions(options)?.w !== 0;\n\n    try {\n      const res = await this.bulkWrite(\n        docs.map(doc => ({ insertOne: { document: doc } })),\n        options\n      );\n      return {\n        acknowledged,\n        insertedCount: res.insertedCount,\n        insertedIds: res.insertedIds\n      };\n    } catch (err) {\n      if (err && err.message === 'Operation must be an object with an operation key') {\n        throw new MongoInvalidArgumentError(","sourceCodeStart":299,"sourceCodeEnd":335,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/collection.ts#L299-L335","documentation":"Thrown by Collection.insertMany when its first argument is not an array. The method's contract requires ReadonlyArray<OptionalUnlessRequiredId<TSchema>>, so a non-array is a programming error and raises a MongoInvalidArgumentError before any I/O. It fails fast to give a clear message rather than a confusing bulk error.","triggerScenarios":"Fires at src/collection.ts:317 when `!Array.isArray(docs)`. Happens if a caller passes a single document object, a generator, a Set, undefined, or null to insertMany.","commonSituations":"Passing a single doc instead of [doc]; destructuring or spreading gone wrong; feeding a Map/Set; passing undefined because a variable was never assigned; refactoring from insertOne without wrapping in an array.","solutions":["Wrap the document(s) in an array: insertMany([doc]).","If you have a single document, use insertOne instead.","Add an Array.isArray guard before the call when the source is dynamic.","Type the variable explicitly so TypeScript catches it at compile time."],"exampleFix":"// before\nawait collection.insertMany({ a: 1 });\n\n// after\nawait collection.insertMany([{ a: 1 }]);","handlingStrategy":"validation","validationCode":"if (!Array.isArray(docs)) {\n  throw new TypeError('docs must be an array');\n}\nawait collection.insertMany(docs);","typeGuard":"function isDocArray(v: unknown): v is Record<string, unknown>[] {\n  return Array.isArray(v) && v.every(d => d != null && typeof d === 'object' && !Array.isArray(d));\n}","tryCatchPattern":null,"preventionTips":["Always pass an array literal to insertMany.","Use insertOne for single documents.","Enable strict TypeScript types on the documents variable."],"tags":["validation","insert","typescript","api-misuse"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}