{"record":{"id":"7d20e06c0b8fd526","repo":"mongodb/node-mongodb-native","slug":"collection-insertmany-cannot-be-called-with-an-a","errorCode":null,"errorMessage":"Collection.insertMany() cannot be called with an array that has null/undefined values","messagePattern":"Collection\\.insertMany\\(\\) cannot be called with an array that has null/undefined values","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/collection.ts","lineNumber":335,"sourceCode":"      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(\n          'Collection.insertMany() cannot be called with an array that has null/undefined values'\n        );\n      }\n      throw err;\n    }\n  }\n\n  /**\n   * Perform a bulkWrite operation without a fluent API\n   *\n   * Legal operation types are\n   * - `insertOne`\n   * - `replaceOne`\n   * - `updateOne`\n   * - `updateMany`\n   * - `deleteOne`\n   * - `deleteMany`\n   *","sourceCodeStart":317,"sourceCodeEnd":353,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/collection.ts#L317-L353","documentation":"Thrown by Collection.insertMany when the input array contains null or undefined entries. Internally insertMany maps each entry to {insertOne:{document:doc}} and calls bulkWrite; the bulk operation rejects non-object operations, and insertMany catches that specific 'Operation must be an object with an operation key' error and rethrows it as this clearer MongoInvalidArgumentError.","triggerScenarios":"Fires at src/collection.ts:335 when the bulk error message matches the operation-key check, which happens because some element of the docs array is null/undefined (sparse array holes, explicit nulls, or undefined from a map/filter).","commonSituations":"Array produced by .map that returns undefined for some items; JSON.parse yielding null entries; sparse arrays like [doc1,,,doc2]; accidental push of undefined; data from an API that includes nulls for missing fields.","solutions":["Filter nullish entries before inserting: docs.filter(d => d != null).","Use flatMap/filter to guarantee dense, non-null arrays.","Validate each element is a plain object before the call.","Enable noUncheckedIndexedAccess / strict checks to catch at compile time."],"exampleFix":"// before\nawait collection.insertMany(records.map(r => r?.payload));\n\n// after\nawait collection.insertMany(records.map(r => r?.payload).filter((d): d is NonNullable<typeof d> => d != null));","handlingStrategy":"validation","validationCode":"const clean = docs.filter((d): d is NonNullable<typeof d> => d != null);\nawait collection.insertMany(clean);","typeGuard":"function hasNoNullish<T>(arr: readonly (T | null | undefined)[]): arr is T[] {\n  return arr.every(d => d != null);\n}","tryCatchPattern":null,"preventionTips":["Filter null/undefined from source arrays before inserting.","Avoid sparse arrays and accidental undefined from .map.","Use strict null checks in TypeScript."],"tags":["validation","insert","data-hygiene","typescript"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}