2016-09-17 49 views
1

我需要在nodejs中創建簡單函數的幫助,這些函數顯示mongodb中某些表中的所有行。如何將mongodb中的數據保存到node.js緩存中?

第二次運行它的函數從node.js緩存中獲取數據,而不是去mongodb。 財產以後這樣的想法:

getData function(){ 

    if(myCache == undefined){ 
     // code that get data from mongodb (i have it) 
     // and insert into cache of node.js (TODO) 
    } 
    else { 
     // code that get data from cache node.js (TODO) 
    } 
} 

回答

0

總的想法是實現某種形式的異步緩存,其中所述高速緩存對象將有一個鍵 - 值存儲。因此,例如,擴展您的想法,您可以重構您的功能以遵循以下模式:

var myCache = {}; 

var getData = function(id, callback) { 
    if (myCache.hasOwnProperty(id)) { 
     if (myCache[id].hasOwnProperty("data")) { /* value is already in cache */ 
      return callback(null, myCache[id].data); 
     } 

     /* value is not yet in cache, so queue the callback */ 
     return myCache[id].queue.push(callback); 
    } 

    /* cache for the first time */ 
    myCache[id] = { "queue": [callback] }; 

    /* fetch data from MongoDB */ 
    collection.findOne({ "_id": id }, function(err, data){ 
     if (err) return callback(err); 

     myCache[id].data = data; 

     myCache[id].queue.map(function (cb) { 
      cb(null, data); 
     }); 

     delete myCache[id].queue; 
    }); 

} 
相關問題