mongodb/node-mongodb-native · error · MongoNotConnectedError

Client must be connected before running operations

Error message

Client must be connected before running operations

What it means

Thrown when an operation needs to auto-connect the client but the client has already been closed (s.hasBeenClosed is true). Once MongoClient.close() runs, the client is permanently unusable; any further operation is rejected rather than silently reconnecting.

Solutions

  1. Defer client.close() until all in-flight operations have completed (e.g. await Promise.allSettled(pending)).
  2. Use a single long-lived MongoClient for the process lifetime; do not close and recreate it per request.
  3. If you need a fresh client, create a new MongoClient rather than reusing a closed one.

Example fix

// before
await client.close();
await collection.insertOne({}); // throws

// after
await collection.insertOne({});
await client.close();
Defensive patterns

Strategy: try-catch

Validate before calling

if (client.s.hasBeenClosed) {
  throw new Error('MongoClient has been closed; create a new client');
}
await collection.findOne({});

Try / catch

try {
  await collection.findOne({});
} catch (e) {
  if (/Client must be connected/.test(e.message)) {
    // create a fresh MongoClient and reconnect
    client = new MongoClient(uri); await client.connect();
  }
}

Prevention

When it happens

Trigger: Calling collection.find(), insertOne(), etc. after awaiting client.close(); sharing a client across a worker pool where one branch closes it while another still issues queries; app shutdown sequences that close the client before draining in-flight requests.

Common situations: Process teardown that closes the DB before async work finishes; test afterEach hooks that close a shared client while a test still has pending queries; refactoring a singleton client into a per-request lifecycle.

Related errors


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

Appendix: source

Thrown at src/operations/execute_operation.ts:147

      timeoutContext,
      session,
      readPreference
    });
  } finally {
    if (session?.owner != null && session.owner === owner) {
      await session.endSession();
    }
  }
}

/**
 * Connects a client if it has not yet been connected
 * @internal
 */
export async function autoConnect(client: MongoClient): Promise<Topology> {
  if (client.topology == null) {
    if (client.s.hasBeenClosed) {
      throw new MongoNotConnectedError('Client must be connected before running operations');
    }
    client.s.options.__skipPingOnConnect = true;
    try {
      await client.connect();
      if (client.topology == null) {
        throw new MongoRuntimeError(
          'client.connect did not create a topology but also did not throw'
        );
      }
      return client.topology;
    } finally {
      delete client.s.options.__skipPingOnConnect;
    }
  }
  return client.topology;
}

/** @internal */

View on GitHub (pinned to dce7939f86)