何时关闭 Nodejs 中的 MongoDB 数据库连接 [英] When to close MongoDB database connection in Nodejs

查看:36
本文介绍了何时关闭 Nodejs 中的 MongoDB 数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 Node MongoDB 本机驱动程序使用 Nodejs 和 MongoDB.需要检索一些文件,并进行修改,然后将它们保存回来.这是一个例子:

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:

db.open(function (err, db) {
  db.collection('foo', function (err, collection) {
    var cursor = collection.find({});
    cursor.each(function (err, doc) {
      if (doc != null) {
        doc.newkey = 'foo'; // Make some changes
        db.save(doc); // Update the document
      } else {
        db.close(); // Closing the connection
      }
    });
  });
});

具有异步性,如果更新文档的过程需要更长的时间,那么当光标到达文档末尾时,数据库连接被关闭.并非所有更新都保存到数据库中.

With asynchronous nature, if the process of updating the document takes longer, then when cursor reaches the end of documents, database connection is closed. Not all updates are saved to the database.

如果省略db.close(),则所有文档都正确更新,但应用程序挂起,永不退出.

If the db.close() is omitted, all the documents are correctly updated, but the application hangs, never exits.

我看到一个帖子建议使用计数器来跟踪更新次数,当回退到零时,然后关闭数据库.但我在这里做错了什么吗?处理这种情况的最佳方法是什么?是否必须使用 db.close() 来释放资源?还是需要打开一个新的数据库连接?

I saw a post suggesting using a counter to track number of updates, when fall back to zero, then close the db. But am I doing anything wrong here? What is the best way to handle this kind of situation? Does db.close() have to be used to free up resource? Or does a new db connection needs to open?

推荐答案

这里有一个基于计数方法的潜在解决方案(我还没有测试它,也没有错误捕获,但它应该传达了这个想法).

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).

基本策略是:获取需要更新多少条记录的计数,异步保存每条记录,成功时回调,如果计数为0,则递减计数并关闭数据库(当最后一次更新完成时)).通过使用{safe:true},我们可以确保每次更新都成功.

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.

mongo 服务器将为每个连接使用一个线程,因此最好 a) 关闭未使用的连接,或 b) 合并/重用它们.

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);
        }
      });
    })
  });
});

这篇关于何时关闭 Nodejs 中的 MongoDB 数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆