mongodb/node-mongodb-native · error · MongoNotConnectedError

MongoClient must be connected to perform this operation

Error message

MongoClient must be connected to perform this operation

What it means

Thrown by the internal getTopology() helper when an operation needs the live Topology object but cannot find one on its provider (a MongoClient, ClientSession, or AbstractCursor). The driver only attaches a Topology after MongoClient.connect() resolves and clears it again on close(), so its absence means the client is not currently connected. It surfaces as a MongoNotConnectedError and is the canonical 'you forgot to connect' signal used by change streams (change_stream.ts) and bulk operations (bulk/common.ts).

Source

Thrown at src/utils.ts:244

  | AbstractCursor
  | Collection<any>
  | Db;

/**
 * A helper function to get the topology from a given provider. Throws
 * if the topology cannot be found.
 * @throws MongoNotConnectedError
 * @internal
 */
export function getTopology(provider: TopologyProvider): Topology {
  // MongoClient or ClientSession or AbstractCursor
  if ('topology' in provider && provider.topology) {
    return provider.topology;
  } else if ('client' in provider && provider.client.topology) {
    return provider.client.topology;
  }

  throw new MongoNotConnectedError('MongoClient must be connected to perform this operation');
}

/** @internal */
export function ns(ns: string): MongoDBNamespace {
  return MongoDBNamespace.fromString(ns);
}

/** @public */
export class MongoDBNamespace {
  db: string;
  collection?: string;
  /**
   * Create a namespace object
   *
   * @param db - database name
   * @param collection - collection name
   */
  constructor(db: string, collection?: string) {

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Ensure `await client.connect()` has resolved before issuing any operation: await it at app startup and only proceed afterwards.
  2. If using a long-lived client, do not call `client.close()` until the process is shutting down; check `client.topology` / `MongoClient.isConnected()` before reusing.
  3. In serverless environments, lazily connect on first use and guard with `if (!client.isConnected()) await client.connect()` rather than connecting at module load.
  4. For change streams/bulk, obtain the db and collection handles after connect() completes, or recreate them after reconnecting.

Example fix

// before
const client = new MongoClient(uri);
const db = client.db('app');
await db.collection('users').insertOne({ name: 'a' }); // throws MongoNotConnectedError

// after
const client = new MongoClient(uri);
await client.connect();
const db = client.db('app');
await db.collection('users').insertOne({ name: 'a' });
Defensive patterns

Strategy: validation

Validate before calling

if (!client.isConnected()) {
  throw new Error('MongoClient is not connected; await client.connect() first');
}
// proceed with the operation

Type guard

function isConnected(client: MongoClient): boolean {
  return typeof client === 'object' && client !== null && client.topology != null;
}

Try / catch

try {
  await operation();
} catch (err) {
  if (err instanceof MongoNotConnectedError) {
    await client.connect();
    await operation(); // single retry after connect
  } else {
    throw err;
  }
}

Prevention

When it happens

Trigger: Calling collection.watch(), collection.initializeUnorderedBulkOp(), or any cursor operation on a MongoClient on which connect() was never awaited, or that was already close()d. Also triggered when constructing a ChangeStream from a db/collection obtained before connect() and then iterating it after close().

Common situations: Forgetting `await client.connect()` (common with copy-pasted samples); reusing a client after `await client.close()`; awaiting connect() in one module but exporting the client before the promise resolves; serverless/lambda cold starts where the cached client was closed between invocations.

Related errors


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