问题描述
我有一些模型,其信息相对较小,希望将其缓存
此数据很少更改
我在npm中寻找软件包,但一无所获,最符合我要求的是 https://www.npmjs.com/package/monc
此库monc
的使用方式是这样
var test = mongoose.model('testModel');
test.find({}).lean().cache().exec(function(err,docs) {
//docs are saved into the cache
});
哪个很好,但是我很难在所有地方都添加.cache()
我想要的是这样的:
var test = mongoose.model('testModel');
test.find({}).lean().exec(function(err,docs) {
// docs are saved into the cache without .cache method
});
正如我所说,我还没有找到任何可以在这方面帮助我的npm软件包,所以我决定自己实现。
这是我的方法
const makeModelCacheable = (model) => {
const _this = model;
_this.cachedData = null;
/** Original exec backup */
_this.originalExec = _this.Query.prototype.exec;
/** Alter exec to verify if cached data is available */
_this.execAlter = function() {
if (!_this.cachedData) {
const data = _this.originalExec.apply(this,arguments);
_this.cachedData = data;
}
return _this.cachedData;
}
/** original exec is overwritten */
_this.Query.prototype.exec = function() {
console.log('exec');
return _this.execAlter.apply(this,arguments);
}
_this.clearCache = function() {
_this.cachedData = null;
}
}
我的方法可以按我想要的方式很好地工作,现在我的问题已解决,但还有其他问题。
当我使用其他型号的猫鼬populate()
时。这是行不通的。他们查询永远不会回来
/* This other data is not cached,'test' model is */
const otherData = await Other.find().populate('test')
假定填充的查询应属于下面的query.exec()
部分,但永远不会
我想实现的是,该模型可以通过find方法进行缓存,并且可以通过populate()
通过其他模型进行缓存(不一定进行缓存),而无需对已经进行的模型查询实现进行太多更改。
预先感谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)