Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 900
nth-chile Avatar asked Aug 29 '18 00:08

nth-chile


1 Answers

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));
}
like image 116
danielgormly Avatar answered Sep 28 '22 19:09

danielgormly