MongoDB "MongoTopologyClosedError: Topology is closed" in CI
The driver tried to use a client whose topology was already closed. In CI this usually means the client was disconnected (often in a test teardown) before a lingering async operation ran, or the connection dropped mid-run.
What this error means
A query fails with "MongoTopologyClosedError: Topology is closed" (older drivers: "Topology was destroyed"), frequently near the end of a test file after close() was called.
MongoTopologyClosedError: Topology is closed
at ClientSession.startTransaction (.../mongodb/lib/sessions.js:200:23)Common causes
The client was closed while work was still pending
An afterAll/teardown called client.close() before an un-awaited query or a background operation completed.
The connection dropped during the run
The mongod service was torn down or the network blipped, closing the topology while the app still held the client.
How to fix it
Await all work before closing the client
- Ensure every query is awaited before teardown.
- Close the client only in a single afterAll, after all tests finish.
- Do not share one client across suites that close independently.
afterAll(async () => {
await client.close();
});Keep the service alive for the whole job
Make sure the mongo service is not stopped until all steps that use it have completed.
How to prevent it
- Await pending operations before closing the client.
- Own client lifecycle in one place per test run.
- Keep the mongod service up for the duration of DB steps.