When to close MongoDB database connection in Nodejs

前端 未结 8 626
一整个雨季
一整个雨季 2020-11-28 21:56

Working with Nodejs and MongoDB through Node MongoDB native driver. Need to retrieve some documents, and make modification, then save them right back. This is an example:

8条回答
  •  一整个雨季
    2020-11-28 22:18

    I found that using counter may apply to simple scenario, but may be hard in complicated situations. Here is a solution that I come up by closing the database connection when database connection is idle:

    var dbQueryCounter = 0;
    var maxDbIdleTime = 5000; //maximum db idle time
    
    var closeIdleDb = function(connection){
      var previousCounter = 0;
      var checker = setInterval(function(){
        if (previousCounter == dbQueryCounter && dbQueryCounter != 0) {
            connection.close();
            clearInterval(closeIdleDb);
        } else {
            previousCounter = dbQueryCounter;
        }
      }, maxDbIdleTime);
    };
    
    MongoClient.connect("mongodb://127.0.0.1:27017/testdb", function(err, connection)(
      if (err) throw err;
      connection.collection("mycollection").find({'a':{'$gt':1}}).toArray(function(err, docs) {
        dbQueryCounter ++;
      });   
      //do any db query, and increase the dbQueryCounter
      closeIdleDb(connection);
    ));
    

    This can be a general solution for any database Connections. maxDbIdleTime can be set as the same value as db query timeout or longer.

    This is not very elegant, but I can't think of a better way to do this. I use NodeJs to run a script that queries MongoDb and Mysql, and the script hangs there forever if the database connections are not closed properly.

提交回复
热议问题