【问题标题】:How to save data from mongodb into node.js cache?如何将数据从 mongodb 保存到 node.js 缓存中?
【发布时间】:2016-09-18 01:09:50
【问题描述】:
我需要帮助在 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)
}
}
【问题讨论】:
标签:
node.js
mongodb
caching
【解决方案1】:
一般的想法是实现某种形式的异步缓存,其中缓存对象将具有键值存储。因此,例如,扩展您的想法,您可以重构您的函数以遵循此模式:
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;
});
}