General question about opening and closing database connections

Hi there. Sorry if I’ve not posted this on the correct forum.
I’ve got a general question about database connections to Mongo. I’m developing an app using Nodejs, Express and a local hosted MongoDB.

The first aspect is more a standard, do a query and then render the results to the browser. Which I open a DB connection, perform the query and close the connection.

The second is an AJAX element, where there could be a number of queries, in quick succession. I have read in this instance it’s best not to close the connection, as this will downgrade the performance.

My question is this, First, is that correct with an AJAX type application. Second, never closing the database connection, will this cause a problem. EG. some kind of out of memory issue when there is a lot of traffic. Or does the connection automatically close after a period of inaction.

Thanks.

You should take the course M220JS as it goes over an application using nodejs.

1 Like

Hello @Andy_Bryan ,

I think @steevej’s suggestion is a solid one. You can go through the M220JS course to get more understanding about implementing the application’s communication with MongoDB using Node.js driver.

Having said that I’d like to add a little into the discussion. The general advice is actually to have a pool of established, ready-to-use connections during the life of the application instead of connecting & disconnecting on every operation. All official drivers do this by default. Please refer to Connection Pool Overview for more details.

With regard to your question:

Second, never closing the database connection, will this cause a problem

No it won’t cause problems as long as the hardware is sized correctly for the workload. Official drivers manage the connections automatically for you to ensure this is as trouble-free as possible. See Connection Monitoring and Pooling if you want to see in detail how this is done.

Regards,
Tarun

2 Likes