【问题标题】:Iterating Objects in Node.JS for HTTP response在 Node.JS 中迭代对象以获取 HTTP 响应
【发布时间】:2012-10-23 07:53:36
【问题描述】:

我在 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.write 吗?

标签: javascript node.js mongodb


【解决方案1】:

response.end() 移出循环。应该这样做。

【讨论】:

    【解决方案2】:

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

    请注意,这将异步附加到流向用户的流中。

    如果您打算一次全部转储,您也可以尝试:

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

    【讨论】:

    • 我改变了 response.end(data);到 response.write(data); response.end();虽然同样的问题仍然存在,但我也尝试将 response.end() 移动到 db.open 的末尾,但这导致根本没有任何响应
    • 最后一次异步回调后需要response.end;在 db.open 结束时可能会在任何写入之前触发。
    • 放在那里但仍然没有迭代,请参阅原始帖子中的代码(已更新)
    • 您的response.end() 不能在那里。阅读代码,它说:“foreach document on this cursor, write the document to the response stream and then end the response stream” ...您实际上是在结束从MongoDB。显然这不是你想要做的。
    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多