Node.js 防止实时流触发多个findOne调用

Node.js 防止实时流触发多个findOne调用,node.js,Node.js,我有一系列事件大致如下: { hash: 'XXXX', foo: 'bar } 每次命中,我都要用猫鼬在数据库中查找哈希 await Model.find({hash: XXX}) 有时,我会遇到一堆共享同一哈希的事件,而当前它会触发一堆本质上返回相同内容的.find()调用 如果哈希相同,如何优化此过程并防止多次调用.find()。有很多方法可以做到这一点。如果列表不长,则使用DB结果保留这些对象的数组。在执行DB查询之前搜索数组 // Disclaimer: This is total

我有一系列事件大致如下:

{ hash: 'XXXX', foo: 'bar }
每次命中,我都要用猫鼬在数据库中查找哈希

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

事件流是什么样子的?就像一个数组{hash:'XXXX',foo:'bar}?如果你分享你正在工作的代码片段,但我没有提到这个“流”实际上是由mongoose集合触发的,那就太好了。注意('change'),所以每个“hit”基本上都是一个对象{hash:'XXXX',foo:'bar}您可以通过以下方式获得唯一的哈希列表:uniqueHashes=new Set(…streamArray.map(item=>item.hash)),然后调用Model.find where hash in uniqueHashes filter感谢您的指针。最终使用了类似的解决方案!