Thursday, 5 September 2013

Keeping open a MongoDB database connection

Keeping open a MongoDB database connection

In so many introductory examples of using MongoDB, you see code like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db)
{
/* Some operation... CRUD, etc. */
db.close();
});
If MongoDB is like any other database system, open and close operations
are typically expensive time-wise.
So, my question is this: Is it OK to simply do the
MongoClient.connect("... once, assign the returned db value to some module
global, have various functions in the module do various database-related
work (insert documents into collections, update documents, etc. etc.) when
they're called by other parts of the application (and thereby re-use that
db value), and then, when the application is done, only then do the close.
In other words, open and close are done once - not every time you need to
go and do some database-related operation. And you keep re-using that db
object that was returned during the initial open\connect, only to dispose
of it at the end, with the close, when you're actually done with all your
database-related work.
Obviously, since all the I/O is asynch, before the close you'd make sure
that the last database operation completed before issuing the close. Seems
like this should be OK, but i wanted to double-check just in case I'm
missing something as I'm new to MongoDB. Thanks!

No comments:

Post a Comment