简体   繁体   English

在Node.JS中迭代对象以获取HTTP响应

[英]Iterating Objects in Node.JS for HTTP response

I have an object array in Node.JS and I wish to response.write(); 我在Node.JS中有一个对象数组,我希望response.write(); it to the screen, I can manage to get the first object out but the loop stops and only the first is outputted, can anybody point me in the right direction... 它到屏幕上,我可以设法得到第一个对象,但循环停止,只有第一个输出,任何人都可以指向正确的方向...

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(); 
                        })                    
                    });
                });

Move response.end() out of the loop. response.end()移出循环。 That should do it. 应该这样做。

You need to change response.end(data); 你需要改变response.end(data); to response.write(data); to response.write(data);

Note that this will asynchronously append to the stream going to the user. 请注意,这将异步附加到发送给用户的流。

If you plan to dump them all at once you can also try: 如果您打算一次性转储它们,您还可以尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM