• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

381
Views
How to close a MongoDB connection in nodejs

I have the following method to connect to MongoDB:

import { Db, MongoClient } from 'mongodb';

let cachedConnection: { client: MongoClient; db: Db } | null = null;

export async function connectToDatabase(mongoUri?: string, database?: string) {
  if (!mongoUri) {
    throw new Error(
      'Please define the MONGO_URI environment variable inside .env.local'
    );
  }

  if (!database) {
    throw new Error(
      'Please define the DATABASE environment variable inside .env.local'
    );
  }

  if (cachedConnection) return cachedConnection;

  cachedConnection = await MongoClient.connect(mongoUri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).then((client) => ({
    client,
    db: client.db(database),
  }));

  return cachedConnection!;
}

And I use it in the following way:

const { db, client } = await connectToDatabase(
  config.URI,
  config.USERS_DATABASE
);

const user = await db
  .collection(config.USERS_COLLECTION)
  .findOne({ _id: new ObjectId(userId) });

It seems to be ok, but it is not. The problem of this method is that it doesn't close the connections. For example I have a cluster on Atlas, and the connections keep growing till 500. after that it doesn't serve anymore, goes in timeout and then my backend crashes.

To solve this I tried with client.close() just before returning the response to frontend.

It throws me one error saying MongoError: Topology is closed, please connect. I believe that it closes the connection before it finishes? is it right? Even if I put it after the DB responded.

this is the screenshot of the error:

enter image description here

Do you think there is a way to solve this or I just have to do the entire procedure in each file I need to connect to mongo? Do you also think I did something wrong?

about 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error