我有一个大致如下的事件流:
{ hash: 'XXXX', foo: 'bar }
在每次命中时,我都要使用mongoose在数据库中查找哈希
await Model.find({hash: XXX})
有时,我会遇到一堆共享相同哈希的事件,当前它会触发一堆.find()
调用,这些调用基本上返回相同的内容。
如果哈希相同,我如何优化此过程并防止.find()
被多次调用。
你有很多方法可以做到这一点。如果列表不长,则使用DB结果保留这些对象的数组。在执行DB查询之前搜索数组。
// Disclaimer: This is total pseudocode - not tested in REPL or anything :)
//
// hashResults as an array of objects like:
// { hash: XXX, data: obj }
let hashResults = [];
const getHashValue = async (hash) => {
const result = hashResults.find(r => r.hash === hash)
if (result) {
return result.data;
} else {
// Do the DB lookup
const data = await Model.find({ hash });
// add to the cache of results
hashResults.push({ hash, data });
return data;
}
}
// However you are looping for the hashes... assuming you have an array of them.
for(h in hashes) {
const val = await getHashValue(h);
}