Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

488
Visualizações
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 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda