Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to manage connections to Mongo with MongoJS?

I'm attempting to use MongoJS as a wrapper for the native Mongo driver in Node. I'm modeling the documents in my collection as JavaScript classes with methods like populate(), save(), etc.

In most languages like C# and Java, I'm used to explicitly connecting and then disconnecting for every query. Most examples only give an example of connecting, but never closing the connection when done. I'm uncertain if the driver is able to manage this on its own or if I need to manually do so myself. Documentation is sparse.

Here's the relevant code:

User.prototype.populate = function(callback) {
    var that = this;    

    this.db = mongo.connect("DuxDB");
    this.db.collection(dbName).findOne({email : that.email}, function(err, doc){
        if(!err && doc) {
            that.firstName  = doc.firstName;
            that.lastName   = doc.lastName;
            that.password   = doc.password;
        }

        if (typeof(callback) === "function"){
            callback.call(that);
        }

        that.db.close();
    });
};

I'm finding that as soon as I call the close() method on the MongoJS object, I can no longer open a new connection on subsequent calls. However, if I do not call this method, the Node process never terminates once all async calls finish, as if it is waiting to disconnect from Mongo.

What is the proper way to manage connections to Mongo with MongoJS?

like image 581
DuxPrime Avatar asked Apr 18 '12 18:04

DuxPrime


2 Answers

You will get better performance from your application if you leave the connection(s) open, rather than disconnecting. Making a TCP connection, and, in the case of MongoDB, discovering the replica set/sharding configuration where appropriate, is relatively expensive compared to the time spent actually processing queries and updates. It is better to "spend" this time once and keep the connection open rather than constantly re-doing this work.

like image 180
dcrosta Avatar answered Sep 27 '22 23:09

dcrosta


Don't open + close a connection for every query. Open the connection once, and re-use it.

like image 33
Barrie Avatar answered Sep 27 '22 22:09

Barrie