【问题标题】:How to close db and http connection如何关闭 db 和 http 连接
【发布时间】:2012-11-05 13:56:13
【问题描述】:

我正在尝试从 MongoDB 读取内容并将内容打印到网页。我正在使用 mongodb 模块从 Mongo 中读取数据。

我能够成功读取数据并将其打印到网页,但我无法确定何时关闭数据库以及何时结束 http 连接。因此我的网页打印结果,但一直在等待服务器发送一些东西。

我提到了以下问题,但不明白在这种特定情况下我需要做什么:

这是我的代码:

/* Opens the secondary collection and goes through each entry*/
var getClientIDs = function(collect, res) {
  db.collection(collect, function(err, collection) {

      var cursor = collection.find();

      cursor.each(function(err, item) {
            if(item != null) {          
            console.log(item['_id'] +"\t" + item['name']);
            res.write(item['_id'].toString());
            res.write("  ");
            res.write(item['name'].toString());
            res.write("</br>");
            }
            /*else {
                res.end("The End"); 
                db.close();     
            } Closes connection before other stuff is done. */
      });
    });

}
/* Opens the main collection and goes through each entry*/
var openCollection = function(collect, res) {
    console.log(green);
    // Establish connection to db
    db.open(function(err, db) {

      // Open a collection
      db.collection(collect, function(err, collection) {

          // Create a cursor
          var cursor = collection.find();

          // Execute the each command, triggers for each document
          cursor.each(function(err, item) {
                if(item != null) {
                getClientIDs(item['_id'], res);
                }
                /* else {
                    db.close();
              }   This closes the connection before other stuff is done */
          });
        });
      });
}
/* Start Here */ 
var http = require('http');
var port = 8888;
http.createServer(function (req, res) {
    res.writeHead(200,{"Content-Type": "text/html; charset=utf-8"});
    openCollection('company',res);
}).listen(port);

db 的方式是有一个名为“company”的集合,其中包含一堆 ID。还有其他同名的 id 集合:

company   = {{ _id: 'A001' }
             { _id: 'A002' }
             { _id: 'A003' }
            }      
A001 = {{_id: "A001-01", "name":"foo"}  
        {_id: "A001-02", "name":"bar"}}

A002 = {{_id: "A002-01", "name":"foo2"}  
        {_id: "A002-02", "name":"bar2"}}

我没有以这种方式创建集合。这就是我必须使用并创建的脚本,该脚本只会在网页上打印 ID 和名称。

使用我的代码,网页打印:

A001-01    foo
A001-02    bar
A002-01    foo2
A002-02    bar2

谢谢。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    当您使用本机驱动程序打开 MongoDB 连接时,您实际上是在打开一个包含 5 个连接的池(默认情况下)。因此,最好在您的应用启动时打开该池并保持打开状态,而不是在每次请求时打开和关闭该池。

    您在关闭 HTTP 响应方面走在了正确的轨道上;只需在响应完成时调用res.end();(即当itemcursor.each 回调中为null 时)。

    【讨论】:

    • 我厌倦了在 item==null 的情况下添加 res.end() 但不会在网页上打印任何内容。虽然我的 console.log() 打印了条目。所以看起来 res.end() 发生在从数据库中获取项目之前。
    • 另外,如果我不关闭数据库连接并刷新浏览器,它会显示Error: db object already connecting, open cannot be called multiple times
    • 我破解了页面刷新时数据库关闭错误的修复程序。我在http.createServer() 中添加了db.close()。每次刷新页面时,都会调用此方法并关闭数据库连接,然后再将责任传递给openCollection()。仍然需要弄清楚关闭http连接。
    • 添加了另一个 hack。我在 10 秒后使用 res.connection.setTimeout(10000) 使页面超时,因此不会让我的浏览器一直等待。这些骇人听闻的修复并不是最好的做法:(
    • @RBK 我并不是说应该让你的代码保持原样而不关闭数据库连接,我的意思是你应该在@987654330 之前将打开数据库池移动到你的应用程序启动@ 称呼。我仔细查看了您的其余代码,但我不明白您为什么要遍历 openConnection 中的集合,然后又在 getClientIDs 中遍历集合中的每个项目。这就是为什么您的 res.end() 呼叫没有按预期工作的原因。
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多