0

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

谢谢你。

4

1 回答 1

1

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

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

于 2012-11-16T21:12:43.053 回答