当将在MongoDB中的NodeJS数据库连接

当将在MongoDB中的NodeJS数据库连接

问题描述:

通过节点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).

的基本策略是:获取多少记录需要更新计数,保存异步每个记录和成功的回调,这将减小计数,并关闭DB如果计数到达0(上次更新完成时)。通过使用 {安全:真正} 我们可以确保每次更新成功

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.

蒙戈服务器将使用每个连接一个线程,所以这是很好的无论是)关闭未使用的连接,或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);
        }
      });
    })
  });
});