如何将mongodb中的数据保存到node.js缓存中?

问题描述:

我需要在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) 
    } 
} 

总的想法是实现某种形式的异步缓存,其中所述高速缓存对象将有一个键 - 值存储。因此,例如,扩展您的想法,您可以重构您的功能以遵循以下模式:

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

}