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

时间:2016-09-17 16:32:59

标签: node.js mongodb caching

我需要帮助在nodejs中创建简单函数,显示mongodb中某些表中的所有行。

第二次运行它的函数从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)
    }
}

1 个答案:

答案 0 :(得分: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;
    });

}
相关问题