2012-10-23 77 views
0

我正在尝试迭代MongoDB游标对象,并从集合中返回所有记录,然后在节点outout中将响应方法用于浏览器。Node.JS HTTP响应返回什么?

我的问题是没有回应似乎被解雇。

我已经尝试把response.end()放入循环中,但它不会遍历结果。

我在不同的地方也尝试过response.end()。下面是代码

db.open(function(err, db) { 
      if(!err) { 
       console.log("Nodelistr is connected to MongoDB\n"); 
       response.writeHead(200); 

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

          //console.dir(doc); 
         })   
         response.end();   
        }); 
       }); 

      }; 

     }); 
+0

'data'未在初始化代码片断您发布 – soulcheck

+0

更新的代码片段。 –

+1

仍未初始化 – soulcheck

回答

0

我无法弄清楚你想要什么与未初始化的变量data做和文件,你在它们之间迭代,但总的问题是,你需要等待调用response.end();,直到您点击光标的末尾。这表示doccursor.each回调中为空。

代码的中间部分应遵循此一般方法:

db.collection('todo', function(err, collection){    
    collection.find(function(err, cursor) { 
     cursor.each(function(err, doc) { 
      if (doc) { 
       ... // initialize data from doc 
       response.write(data); 
      } else { 
       // doc is null, so the cursor is exhausted 
       response.end();   
      } 
     })   
    }); 
});