When to close MongoDB database connection in Nodejs

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

    Here's a potential solution based on the counting approach (I haven't tested it and there's no error trapping, but it should convey the idea).

    The basic strategy is: Acquire the count of how many records need to be updated, save each record asynchronously and a callback on success, which will decrement the count and close the DB if the count reaches 0 (when the last update finishes). By using {safe:true} we can ensure that each update is successful.

    The mongo server will use one thread per connection, so it's good to either a) close unused connections, or b) pool/reuse them.

    db.open(function (err, db) {
      db.collection('foo', function (err, collection) {
        var cursor = collection.find({});
        cursor.count(function(err,count)){
          var savesPending = count;
    
          if(count == 0){
            db.close();
            return;
          }
    
          var saveFinished = function(){
            savesPending--;
            if(savesPending == 0){
              db.close();
            }
          }
    
          cursor.each(function (err, doc) {
            if (doc != null) {
              doc.newkey = 'foo'; // Make some changes
              db.save(doc, {safe:true}, saveFinished);
            }
          });
        })
      });
    });
    

提交回复
热议问题