2012-07-23 19 views
0

我的品牌新的Node.js(不到一小時)。範圍界定在node.js中,MongoDB的+ HTTP服務器循環

我試圖彈出來讀取某個MongoDB的收集和數據打印到瀏覽器窗口,一個簡單的HTTP服務器。

到目前爲止,我有:

var http = require ("http") 
var mongodb = require('mongodb'); 

http.createServer(function(request, response) { 
    var server = new mongodb.Server("127.0.0.1", 27107, {}); 
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.write('Collection Data:<br>') 
    new mongodb.Db('testdb', server, {}).open(function (error, client) { 
     if (error) throw error; 
     var collection = new mongodb.Collection(client, 'test_coll'); 
     collection.find({}, {limit:100}).each(function(err, doc) { 
     if (doc != null) { 
      console.dir(doc.text); 
      response.write(doc.text) 
     } 
     }); 
     response.write("some stuff") 
     response.end(); 
    }); 
}).listen(8080) 

這使藏品的文本到控制檯,而不是瀏覽器窗口。我認爲這是因爲響應對象不在.each回調中的作用域中。我的結構是錯誤的嗎?

回答

2

的問題是,response.end()被稱爲回調執行之前。

你必須回到屋裏去,就像這樣:

collection.find({}, {limit:100}).each(function(err, doc){ 
    if (doc != null) { 
     console.dir(doc.text); 
     response.write(doc.text) 
    } else { 
     // null signifies end of iterator 
     response.write("some stuff"); 
     response.end(); 
    } 
}); 
+0

好吧,我看到了,但那也沒有做到 - 它將一個打印到客戶端,然後結束響應。 – fields 2012-07-23 17:11:01

+0

仍然沒有骰子:類型錯誤:對象#沒有法「的forEach」 – fields 2012-07-23 17:19:51

+0

這似乎仍然沒有做到這一點。任何事情,我把cursor.each()之後,但在回調函數內,仍然得到來自cursor.each輸出之前執行()發生。如果我將response.end()留在那裏,我所得到的只是「一些東西」。如果我完全取出response.end(),我會得到「一些東西」,然後是我所期望的所有mongo數據。據推測,至少在這個例子中,我想真正關閉的要求,雖然我的地方的下一步列表上打開網絡插座,因爲它變得可用,將連續讀取數據。有沒有辦法讓光標讀取塊? – fields 2012-07-23 17:50:51

0

res.end有發生後的回調內部循環:

client.collection('test_coll', function(err, testColl) { 
    testColl.find({}).each(function(err, doc) { 
    if (err) { 
     // handle errors 
    } else if (doc) { 
     res.write(doc._id + ' ') 
    } else { // If there's no doc then it's the end of the loop 
     res.end() 
    } 
    }) 
})