{"record":{"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/dce7939f86fb283e167ad709955abedb7bf23124/src/utils.ts#L226-L262","documentation":"Thrown by getTopology() when neither the provider (MongoClient/ClientSession/AbstractCursor) nor its .client has a non-falsy topology property. The topology is set during MongoClient.connect(); if it is absent the client was never connected or has been closed. Raised as MongoNotConnectedError.","triggerScenarios":"Calling collection.find(), db.command(), or cursor methods before awaiting client.connect() (or before any operation that would auto-connect). Also after client.close() when a stale Db/Collection reference is reused. Or when awaiting client.connect() is skipped because the operation was invoked synchronously at module load.","commonSituations":"Forgetting to await client.connect() in older driver versions (pre-4.x auto-connect is typical but not guaranteed in all code paths), reusing collection/db handles after client.close(), or referencing a collection before the connect promise resolves.","solutions":["Ensure await client.connect() has resolved before issuing operations, or rely on lazy connect (first operation) but avoid reusing handles after close().","Do not reuse Db/Collection objects obtained from a MongoClient after calling client.close(); create a new client and reconnect.","Check client topology readiness or guard with try/catch around operations that may run before connection."],"exampleFix":"// before\nconst client = new MongoClient(uri);\nconst db = client.db('test');\ndb.collection('c').findOne(); // not connected yet\n\n// after\nconst client = new MongoClient(uri);\nawait client.connect();\nconst db = client.db('test');\nawait db.collection('c').findOne();","handlingStrategy":"validation","validationCode":"await client.connect();\nif (!client.topology) throw new Error('Client failed to connect');\n// now safe to run operations","typeGuard":"function isClientConnected(client: import('mongodb').MongoClient): boolean {\n  return !!client.topology;\n}","tryCatchPattern":"try {\n  await collection.findOne(filter);\n} catch (e) {\n  if (e instanceof MongoNotConnectedError) {\n    await client.connect();\n    await collection.findOne(filter);\n  } else throw e;\n}","preventionTips":["Await client.connect() before issuing operations (or rely on first-op lazy connect).","Never reuse Db/Collection handles from a client after client.close(); create a new client.","Centralize client lifecycle in your app bootstrap to avoid using stale references."],"tags":["connection","lifecycle","initialization"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}