{"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/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/collection.ts#L317-L353","documentation":"Thrown by Collection.insertMany() when the docs array contains one or more null/undefined elements. Internally insertMany maps each doc to { insertOne: { document: doc } } and calls bulkWrite; bulk's raw() rejects null/undefined operations with 'Operation must be an object with an operation key', which insertMany catches and rewrites into this clearer message. It is a MongoInvalidArgumentError surfaced before the bulk is sent to the server.","triggerScenarios":"An array built with sparse holes or pushed undefined: docs.push(maybeDoc) where maybeDoc is undefined; JSON arrays containing null literals ([{a:1}, null]); destructuring or mapping that yields undefined for missing keys; mixing documents and null sentinels.","commonSituations":"Reading rows from a CSV/database where some rows are null and pushing them unfiltered; array built from Object.values on a sparse object; conditional spread that inserts undefined; migrating code that previously tolerated nulls.","solutions":["Filter null/undefined before the call: await collection.insertMany(docs.filter(d => d != null)).","Find and fix the producer of the null/undefined entries so the array is always dense.","If null should mean 'skip', validate with docs.every(d => d != null) and reject early with a descriptive error.","Add a unit test asserting the array has no holes after it is constructed."],"exampleFix":"// before\nconst docs = rows.map(r => r.isValid ? r.asDocument() : undefined);\nawait collection.insertMany(docs);\n// after\nconst docs = rows.map(r => r.asDocument()).filter((d): d is NonNullable<typeof d> => d != null);\nawait collection.insertMany(docs);","handlingStrategy":"validation","validationCode":"function sanitizeDocs<T>(docs: (T | null | undefined)[]): T[] {\n  const clean = docs.filter((d): d is T => d != null);\n  if (clean.length !== docs.length) {\n    // optional: log how many were dropped\n  }\n  return clean;\n}\nawait collection.insertMany(sanitizeDocs(rawDocs));","typeGuard":"const isDenseDocumentArray = <T>(v: unknown): v is T[] =>\n  Array.isArray(v) && v.every(d => d != null && typeof d === 'object' && !Array.isArray(d));","tryCatchPattern":"try {\n  await collection.insertMany(docs);\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /null\\/undefined values/.test(e.message)) {\n    const cleaned = docs.filter(d => d != null);\n    return collection.insertMany(cleaned); // or surface a domain error\n  }\n  throw e;\n}","preventionTips":["Never push undefined into a docs array; filter at the source.","Type builders as returning NonNullable<T>[].","Add a unit test asserting the built array has no holes."],"tags":["validation","crud","insert","null-safety"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}