When to close a MongoDB connection When to close a MongoDB connection database database

When to close a MongoDB connection


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));}