mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Argument "iterator" must be a function

Error message

Argument "iterator" must be a function

What it means

Thrown by the deprecated cursor.forEach(iterator) when the iterator argument is not a function. forEach is a callback-pattern API; the driver invokes it once per document and a non-callable argument cannot be invoked.

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 3366c21a63)

Solutions

  1. Pass an actual function: cursor.forEach(doc => handle(doc)).
  2. Prefer `for await (const doc of cursor)` — forEach is deprecated.
  3. Double-check that bundlers/minifiers did not stringify the callback.

Example fix

// before
cursor.forEach('doc => handle(doc)');
// after
for await (const doc of cursor) { handle(doc); }
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof iterator !== 'function') throw new TypeError('iterator must be a function');
cursor.forEach(iterator);

Type guard

function isFunction(v): v is Function { return typeof v === 'function'; }

Prevention

When it happens

Trigger: Calling cursor.forEach(null), cursor.forEach(undefined), cursor.forEach('doc => ...') (string instead of function), or passing an async function wrapped in quotes. Also passing an arrow function that was destructured/lost.

Common situations: Migrating from callback-style to async/await and forgetting to convert forEach to for-await; passing a method reference that was unbound and overridden; copy-paste leaving a string literal.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04). Data as JSON: /data/errors/00238d7a10476b29.json. Report an issue: GitHub.