Leaving the DB connection alive

In docs you’ll come across many examples like this

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db)
{
    /* Some operation... CRUD, etc. */
    db.close();
});

after some operation they close the connection, but my question is
Is it safe to keep the connection (once successfully connected) to keep it alive for the rest of time ( may for days or months)
Because I tried to keep it alive and use the same opened connection in rest of my app, and it significantly increase my performance.
Thanks in advance

It is best practice to keep the connection open between your application and the database server.

The code snippet you provided is usually implemented as:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db)
{
    applicationMainFunction( db );
    db.close();
});
1 Like

Hi @HSD_Qatar, welcome to the community.
Keeping the connection alive is totally fine, if proper network and security configurations have been applied in line with MongoDB best practices then there shouldn’t be any additional security safety concerns. Here are some resources which can help you in ensuring that:

Please note, that the above resources are for your own (non-Atlas) MongoDB deployments.
Having said that, Atlas adds even more to secure deployments:

In case you have any doubts, please feel free to reach out to us.

Thanks. Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

1 Like

Thank you, Understood.
The links you provided are awesome

1 Like