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?

1

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What is a controlled shutdown? Is the connection pool built into the mongodb package?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.