6

我正在开发我的第一个 node.js / express / mongoose 应用程序,由于 node.js 的异步机制,我面临一个问题。看来我没有正确地做这件事......

这是我使用 express 定义的测试路线:

app.get('/test', function(req, res){
  var mod = mongoose.model('MyModel');
  mod.find({},function(err, records){
    records.forEach(function(record){
      console.log('Record found:' + record.id);
      // res.send('Thing retrieved:' + record.id);
    });
  });
});

当我发出http://localhost/test时,我想在响应中获取“MyModel”类型的记录列表。

上面的代码运行良好,但是在将整个列表返回给客户端时......它不起作用(注释的 res.send 行)并且只返回了第一条记录。

我对 node.js 很陌生,所以我不知道在 app.get 的第一个回调函数中嵌入几个回调函数是否是一个好的解决方案。我怎么能把整个名单都退回来?

任何想法 ?

4

1 回答 1

10

你应该做的是:

mod.find({},function(err, records){
  res.writeHead(200, {'Content-Length': body.length});
  records.forEach(function(record){
    res.write('Thing retrieved:' + record.id);
  });
});

请始终检查文档:

http://nodejs.org/docs/v0.3.8/api/http.html#response.write

我错过了您使用 express,发送函数是 express 的一部分,并且扩展了节点的 serverResponse 对象(我的错)。

但我的回答仍然适用,express 的发送函数使用ServerResponse.end()所以那里的套接字 get 关闭并且您不能再发送数据,使用 write 函数使用本机函数发送数据。

您可能还想res.end()在请求完全完成后致电,因为快递中的某些物品可能会受到影响

于 2011-04-09T22:26:29.000 回答