When to close MongoDB database connection in Nodejs

前端 未结 8 603
一整个雨季
一整个雨季 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:32

    It's best to use a pooled connection and then call db.close() in cleanup function at the end of your application's life:

    process.on('SIGINT', cleanup);
    process.on('SIGTERM', cleanup);
    

    See http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html

    A bit old thread, but anyway.

    0 讨论(0)
  • 2020-11-28 22:35

    I came up with a solution that involves a counter like this. It does not depend on a count() call nor does it wait for a time out. It will close the db after all the documents in each() are exhausted.

    var mydb = {}; // initialize the helper object.
    
    mydb.cnt = {}; // init counter to permit multiple db objects.
    
    mydb.open = function(db) // call open to inc the counter.
    {
      if( !mydb.cnt[db.tag] ) mydb.cnt[db.tag] = 1;
      else mydb.cnt[db.tag]++;
    }; 
    
    mydb.close = function(db) // close the db when the cnt reaches 0.
    {
      mydb.cnt[db.tag]--;
      if ( mydb.cnt[db.tag] <= 0 ) {
        delete mydb.cnt[db.tag];
        return db.close();
      }
      return null;
    };
    

    So that each time you are going to make a call like db.each() or db.save() you would use these methods to ensure the db is ready while working and closed when done.

    Example from OP:

    foo = db.collection('foo');
    
    mydb.open(db); // *** Add here to init the counter.**  
    foo.find({},function(err,cursor)
    {
      if( err ) throw err; 
      cursor.each(function (err, doc)
      {
        if( err ) throw err;
        if (doc != null) {
          doc.newkey = 'foo';
          mydb.open(db); // *** Add here to prevent from closing prematurely **
          foo.save(doc, function(err,count) {
            if( err ) throw err;
            mydb.close(db); // *** Add here to close when done. **
          }); 
        } else {
          mydb.close(db); // *** Close like this instead. **
        }
      });
    });
    

    Now, this assumes that the second to last callback from each makes it through the mydb.open() before the last callback from each goes to mydb.close().... so, of course, let me know if this is an issue.

    So: put a mydb.open(db) before a db call and put a mydb.close(db) at the return point of the callback or after the db call (depending on the call type).

    Seems to me that this kind of counter should be maintained within the db object but this is my current workaround. Maybe we could create a new object that takes a db in the constructor and wrap the mongodb functions to handle the close better.

    0 讨论(0)
提交回复
热议问题