4

I read this article on connection pooling with mongodb/nodejs. There he opens the connection once, and leaves it at that.

This is how I set up the database connection in my app.js file:

mongodb.MongoClient.connect(MONGODB_URI, function (error, database) {
    if (error) throw error;

    db = database; // db is defined outside this callback
    coll = db.collection('testData'); // coll is defined outside this callback
});

This is going to leave the db connection open as long as the server is running. Shouldn't you close the connection at some point? Or is it of no consequence to leave it open?

ptf
  • 3,210
  • 8
  • 34
  • 67
  • 1
    Refer http://stackoverflow.com/questions/14495975/why-is-it-recommended-not-to-close-a-mongodb-connection-anywhere-in-node-js-code – Damodaran May 10 '14 at 12:56

1 Answers1

2

If your app has support for controlled shutdown, then you should close the connection pool at that time. Otherwise you just leave it open.

The connection pool manages the number of actual connections for you, adding more in times of heavy load and closing them when your app is idle.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • What is a controlled shutdown? Is the connection pool built into the mongodb package? – ptf May 10 '14 at 13:10
  • @kjelelokk A controlled shutdown is just a general term for a program's support for closing in an orderly manner that ensures all outstanding operations have completed, as opposed to the default `ctrl+c` close. Yes, the standard `MongoClient` you reference above is a connection pool, not a single connection. – JohnnyHK May 10 '14 at 13:15