如何关闭db和http连接

时间:2012-11-16 19:48:00

标签: node.js mongodb

我正在尝试从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

谢谢。

1 个答案:

答案 0 :(得分:1)

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

您正在通过关闭HTTP响应走上正轨;只需在回复完成后致电res.end();(即item回调中nullcursor.each)。