简体   繁体   中英

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?

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.

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

Do something more like this reusing your db connection for all calls

User = function(db) {
  this.db = db;
}


User.prototype.populate = function(callback) {
  var that = this;  
  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);
      }
  });
};

我相信它实际上会在每次请求后关闭连接,但它会在mongodb服务器配置中设置{auto_reconnect:true},因此无论何时需要,它都会重新打开一个新连接。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM