mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Collection.insertMany() cannot be called with an array that…

Error message

Collection.insertMany() cannot be called with an array that has null/undefined values

What it means

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.

Solutions

  1. Filter nullish entries before inserting: docs.filter(d => d != null).
  2. Use flatMap/filter to guarantee dense, non-null arrays.
  3. Validate each element is a plain object before the call.
  4. Enable noUncheckedIndexedAccess / strict checks to catch at compile time.

Example fix

// before
await collection.insertMany(records.map(r => r?.payload));

// after
await collection.insertMany(records.map(r => r?.payload).filter((d): d is NonNullable<typeof d> => d != null));
Defensive patterns

Strategy: validation

Validate before calling

const clean = docs.filter((d): d is NonNullable<typeof d> => d != null);
await collection.insertMany(clean);

Type guard

function hasNoNullish<T>(arr: readonly (T | null | undefined)[]): arr is T[] {
  return arr.every(d => d != null);
}

Prevention

When it happens

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

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

Related errors


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

Appendix: source

Thrown at src/collection.ts:335

      throw new MongoInvalidArgumentError('Argument "docs" must be an array of documents');
    }
    options = resolveOptions(this, options ?? {});

    const acknowledged = WriteConcern.fromOptions(options)?.w !== 0;

    try {
      const res = await this.bulkWrite(
        docs.map(doc => ({ insertOne: { document: doc } })),
        options
      );
      return {
        acknowledged,
        insertedCount: res.insertedCount,
        insertedIds: res.insertedIds
      };
    } catch (err) {
      if (err && err.message === 'Operation must be an object with an operation key') {
        throw new MongoInvalidArgumentError(
          'Collection.insertMany() cannot be called with an array that has null/undefined values'
        );
      }
      throw err;
    }
  }

  /**
   * Perform a bulkWrite operation without a fluent API
   *
   * Legal operation types are
   * - `insertOne`
   * - `replaceOne`
   * - `updateOne`
   * - `updateMany`
   * - `deleteOne`
   * - `deleteMany`
   *

View on GitHub (pinned to dce7939f86)