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

450
Visualizações
When to close a MongoDB connection

For context, I am writing an ExpressJS app and using the MongoDB node driver, mongodb.

The app will need to talk to the remote DB rapidly at times, depending on how often users are doing things. I understand that the app shouldn't open and close a connection each time it needs data. It should connect once, and there should be an thing named db that you can use for querying, example: db.collection("users").find(...), and all future DB calls should just use that db variable.

But if I deploy my app, I am assuming that server.js just executes once at the beginning of the app's life. That would mean that one connection is made once in the entire lifespan of that deployment.

But don't these connections time out? Do I just check that the db var is an open connection, and if not, reconnect before making a call?

Surprisingly, I haven't found many guides, so I don't know the right way, which is why I am asking here. Please let me know if I can ask this question in a better way.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You don't have to manage the connection yourself. The MongoClient.connect call comes with batteries included. See the docs: the connect methods includes a autoReconnect (defaults to true) which will attempt to keep the connection available. You also have poolSize (defaults to 5) to give the client (that you can save and reuse throughout your app) the opportunity to use more than 1 connection.

Adding full example:

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';

MongoClient.connect(url)
    .then(client => runMyApp(client));

function runMyApp(client) {
    // Use client however you like e.g.
    client.db('users').find({})
        .then((results) => console.log(results));
}
over 4 years ago · Santiago Trujillo Relatório
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