【问题标题】:Scoping in node.js, mongodb + http server loopnode.js,mongodb + http服务器循环中的范围
【发布时间】:2012-07-21 22:52:49
【问题描述】:

我是 node.js 的新手(不到一小时)。

我正在尝试启动一个简单的 http 服务器,它将读取 mongodb 集合并将数据打印到浏览器窗口。

到目前为止,我有:

var http = require ("http")
var mongodb = require('mongodb');

http.createServer(function(request, response) {
    var server = new mongodb.Server("127.0.0.1", 27107, {});
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write('Collection Data:<br>')
    new mongodb.Db('testdb', server, {}).open(function (error, client) {
      if (error) throw error;
      var collection = new mongodb.Collection(client, 'test_coll');
      collection.find({}, {limit:100}).each(function(err, doc) {
        if (doc != null) {
            console.dir(doc.text);
            response.write(doc.text)
        }
      });
      response.write("some stuff")
      response.end();
    });
}).listen(8080)

这会将集合项的文本放在控制台上,而不是放在浏览器窗口上。我认为这是因为响应对象不在 .each 回调的范围内?我的结构是否错误?

【问题讨论】:

    标签: node.js mongodb scope


    【解决方案1】:

    res.end 必须在回调内的 for 循环之后发生:

    client.collection('test_coll', function(err, testColl) {
      testColl.find({}).each(function(err, doc) {
        if (err) {
            // handle errors
        } else if (doc) {
            res.write(doc._id + ' ')
        } else { // If there's no doc then it's the end of the loop
            res.end()
        }
      })
    })
    

    【讨论】:

      【解决方案2】:

      问题是response.end() 在您的回调执行之前被调用。

      你必须把它移到里面,像这样:

      collection.find({}, {limit:100}).each(function(err, doc){
          if (doc != null) {
              console.dir(doc.text);
              response.write(doc.text)
          } else {
              // null signifies end of iterator
              response.write("some stuff");
              response.end();
          }
      });
      

      【讨论】:

      • 好的,我明白了,但这也不行——它会向客户端打印一个,然后结束响应。
      • 仍然没有骰子:TypeError: Object # has no method 'forEach'
      • 这似乎还是不行。我在 cursor.each() 之后但在回调函数中放置的任何内容,仍然会在 cursor.each() 的输出发生之前执行。如果我将 response.end() 留在那里,我得到的只是“一些东西”。如果我完全取出 response.end(),我会得到“一些东西”,然后是我期望的所有 mongo 数据。据推测,至少在这个例子中,我想真正关闭请求,尽管我接下来的步骤列表中的某个地方是打开一个 Web 套接字,它将在数据可用时连续读取数据。有没有办法让光标读取块?
      • @fields 这最终回答了你的问题吗?
      猜你喜欢
      • 2018-08-12
      • 2015-09-20
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2014-11-13
      • 2016-08-03
      • 1970-01-01
      相关资源
      最近更新 更多