Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

441
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!