2014-02-19 104 views
8

我正在尋找通過Node.js服務器層將數據從MongoDB流式傳輸到Web客戶端的最佳方式。我正在請求每個查詢約10MB的數據,並且查詢已在day_timestamp上編入索引。注意,I have already read this post.Node.js,Express,MongoDB和流

我使用的唯一蒙戈相關模塊如下(我需要別人來實現自己的目標?):

MongoClient = require('mongodb').MongoClient; 

目前我的代碼看起來是這樣的:

MongoClient.connect('mongodb://host:port/myDatabase', function(err, db) { 
    if(err) throw err; 
    console.log("Connected to Database"); 

    // Server picks up URL requests made by browser 
    app.get("/:type/:category/:resolution/:from/:to/", function (req, res){ 
     var start = moment(); 

     var type = String(req.params.type) 
      ,category = String(req.params.category) 
      ,resolution = String(req.params.resolution) 
      ,from = moment.utc(req.params.from).toDate() 
      ,to = moment.utc(req.params.to).toDate() 
      ,options = { 
       parse : true, 
       accept : 'application/json' 
      }; 

     res.set('Content-Type', 'application/json'); // Required? 
     res.writeHead(200, { 'Content-Type': 'application/json'}); // Required? 
     var collection = db.collection(category); 
     var stream = collection.find({'day_timestamp':{'$gte':from, '$lte':to}}) 
      .sort({day_timestamp:1}) 
      .stream() 
      .pipe(JSONStream.stringify()) 
      .pipe(res) 
    }); 
}); 

這個工程,但似乎沒有提供任何性能收益相比,一個'正常'collection.find()回調嵌套res.json(...);

我想了解一些事情。首先,我想將數據從MongoDB直接傳輸到我的Nods.js服務器......並且一旦它到達我的服務器,就直接將它流式傳輸到客戶端。如果需要的話,這可以是BSON,我可以在客戶端反序列化它。這可能嗎?

其次,我將如何去添加一個例子來計時這個流的性能與正常的collection.find()回調?在後面的例子中,我可以很容易地做到這一點,但我不清楚我將如何處理流例子(因爲.pipe,nb stream.end似乎不可能工作)

第三,我試圖儘可能快地從MongoDB獲取數據到我的客戶端,而我的Node.js不需要做太多(如果有的話)數據處理,因爲數據按照需要存儲在數據庫中。我是否在談論寫作方式來實現這一目標?

+1

21看法?這是一個熱門話題,沒有答案:(? – jtromans

+0

爲什麼使用JSONStream?直接管道:http://mongoosejs.com/docs/api.html#querystream_QueryStream-pipe – malix

+0

感謝30個月後的評論;)不記得如何我現在解決了。 – jtromans

回答

1

這每一個有數據寫入時間寫入res

var stream = collection.find({'day_timestamp':{'$gte':from, '$lte':to}}) 
    .sort({day_timestamp:1}) 
    .stream(); 

stream.on('data', function(data) { 
    res.write(JSON.stringify(data)); 
}); 

stream.on('end', function() { 
    res.end(); 
});