{"id":"18edb275020cfcc3","repo":"mongodb/node-mongodb-native","slug":"mongoclient-must-be-connected-to-perform-this-oper","errorCode":null,"errorMessage":"MongoClient must be connected to perform this operation","messagePattern":"MongoClient must be connected to perform this operation","errorType":"exception","errorClass":"MongoNotConnectedError","httpStatus":null,"severity":"error","filePath":"src/utils.ts","lineNumber":244,"sourceCode":"  | AbstractCursor\n  | Collection<any>\n  | Db;\n\n/**\n * A helper function to get the topology from a given provider. Throws\n * if the topology cannot be found.\n * @throws MongoNotConnectedError\n * @internal\n */\nexport function getTopology(provider: TopologyProvider): Topology {\n  // MongoClient or ClientSession or AbstractCursor\n  if ('topology' in provider && provider.topology) {\n    return provider.topology;\n  } else if ('client' in provider && provider.client.topology) {\n    return provider.client.topology;\n  }\n\n  throw new MongoNotConnectedError('MongoClient must be connected to perform this operation');\n}\n\n/** @internal */\nexport function ns(ns: string): MongoDBNamespace {\n  return MongoDBNamespace.fromString(ns);\n}\n\n/** @public */\nexport class MongoDBNamespace {\n  db: string;\n  collection?: string;\n  /**\n   * Create a namespace object\n   *\n   * @param db - database name\n   * @param collection - collection name\n   */\n  constructor(db: string, collection?: string) {","sourceCodeStart":226,"sourceCodeEnd":262,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/utils.ts#L226-L262","documentation":"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).","triggerScenarios":"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().","commonSituations":"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.","solutions":["Ensure `await client.connect()` has resolved before issuing any operation: await it at app startup and only proceed afterwards.","If using a long-lived client, do not call `client.close()` until the process is shutting down; check `client.topology` / `MongoClient.isConnected()` before reusing.","In serverless environments, lazily connect on first use and guard with `if (!client.isConnected()) await client.connect()` rather than connecting at module load.","For change streams/bulk, obtain the db and collection handles after connect() completes, or recreate them after reconnecting."],"exampleFix":"// before\nconst client = new MongoClient(uri);\nconst db = client.db('app');\nawait db.collection('users').insertOne({ name: 'a' }); // throws MongoNotConnectedError\n\n// after\nconst client = new MongoClient(uri);\nawait client.connect();\nconst db = client.db('app');\nawait db.collection('users').insertOne({ name: 'a' });","handlingStrategy":"validation","validationCode":"if (!client.isConnected()) {\n  throw new Error('MongoClient is not connected; await client.connect() first');\n}\n// proceed with the operation","typeGuard":"function isConnected(client: MongoClient): boolean {\n  return typeof client === 'object' && client !== null && client.topology != null;\n}","tryCatchPattern":"try {\n  await operation();\n} catch (err) {\n  if (err instanceof MongoNotConnectedError) {\n    await client.connect();\n    await operation(); // single retry after connect\n  } else {\n    throw err;\n  }\n}","preventionTips":["Await client.connect() once at application startup and store the connected promise so importers can await it.","In long-running servers, never call close() except on shutdown.","In serverless, guard with isConnected() and lazily connect on each cold start."],"tags":["connection","lifecycle","startup"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}