在Node.JS中迭代对象以进行HTTP响应

我在Node.JS中有一个对象数组,我希望response.write(); 它到屏幕上,我可以设法得到第一个对象,但循环停止,只有第一个输出,有人可以指向我在正确的方向…

db.collection('todo', function(err, collection){ collection.find(function(err, cursor) { cursor.each(function(err, doc) { for(docs in doc){ if(docs == "_id"){ }else{ var test = docs + " : " + doc[docs]; } } data = data.toString("utf8").replace("{{TEST}}", test); response.write(data); response.end(); }) }); }); 

response.end()移出循环。 这应该做到这一点。

你需要改变response.end(data);response.write(data);

请注意,这将asynchronous追加到去往用户的stream。

如果您打算立即转储它们,您也可以尝试:

 cursor.toArray(function (err, docs) { /** run a for loop over each doc in docs **/ })