mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Argument "iterator" must be a function

Error message

Argument "iterator" must be a function

What it means

Thrown as a MongoInvalidArgumentError from forEach() when the iterator argument fails `typeof iterator !== 'function'`. forEach() drives iteration by invoking the callback once per document and stopping when it returns false, so a non-callable argument would fail at the first document at runtime; the constructor-style guard fails fast with a precise message instead. The method is also deprecated in favor of for-await iteration.

Solutions

  1. Pass an actual function: cursor.forEach(doc => { ... }).
  2. Migrate to for await (const doc of cursor) { ... } which is the non-deprecated replacement.
  3. If the callback is optional in your code, default it to a no-op function or branch before calling forEach().

Example fix

// before: callback is undefined / not a function
await cursor.forEach(processDocs); // processDocs is undefined

// after: pass a real function, or use for-await
await cursor.forEach(doc => handle(doc));
// preferred:
for await (const doc of cursor) handle(doc);
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof iterator !== 'function') {
  throw new TypeError('forEach requires a function argument');
}
await cursor.forEach(iterator);

Type guard

function isIterator(v: unknown): v is (doc: any) => boolean | void {
  return typeof v === 'function';
}

Prevention

When it happens

Trigger: Calling cursor.forEach(undefined), cursor.forEach(null), cursor.forEach('doc => {}') (string instead of function), or cursor.forEach(someObject); passing a value that was supposed to be a callback but was conditionally undefined.

Common situations: Refactoring a forEach call and forgetting to pass the callback; passing a function name that is typo'd or shadowed to undefined; mixing callback-style and async-iterator styles.

Related errors


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

Appendix: source

Thrown at src/cursor/abstract_cursor.ts:626

      }
    }

    return null;
  }

  /**
   * Iterates over all the documents for this cursor using the iterator, callback pattern.
   *
   * If the iterator returns `false`, iteration will stop.
   *
   * @param iterator - The iteration callback.
   * @deprecated - Will be removed in a future release. Use for await...of instead.
   */
  async forEach(iterator: (doc: TSchema) => boolean | void): Promise<void> {
    this.signal?.throwIfAborted();

    if (typeof iterator !== 'function') {
      throw new MongoInvalidArgumentError('Argument "iterator" must be a function');
    }
    for await (const document of this) {
      const result = iterator(document);
      if (result === false) {
        break;
      }
    }
  }

  /**
   * Frees any client-side resources used by the cursor.
   */
  async close(options?: { timeoutMS?: number }): Promise<void> {
    await this.cleanup(options?.timeoutMS);
  }

  /**
   * Returns an array of documents. The caller is responsible for making sure that there

View on GitHub (pinned to dce7939f86)