我想对mongo集合进行查询,当集合发生变化时,我想再次运行查询。但是为了优化它,我不想在每次集合更改时都运行查询,只有当与查询匹配的文档更改时才运行查询。我有以下代码:
const query = { author: someUserID };
const fetch = async () => await collection.find(query).toArray();
const watcher = collection
.watch([{ $match: { fullDocument: query } }])
.on("change", () => fetch().then(sendData)); // This does not work
fetch().then(sendData); // This works在第一次运行时,它将获取文档并执行sendData,但是当插入新文档时,该事件不会被触发。当我在不带参数的情况下运行collection.watch()时,它可以正常工作。
问题出在哪里?谢谢。
编辑:我希望能够为.find()和.watch()重用query。
发布于 2020-09-16 08:59:29
该示例中$match阶段本质上是
{$match: { fullDocument: { author: someUserId }}}只有当fullDocument恰好是{ author: someUserId }且没有其他字段或值时,才会匹配。
为了匹配作者,同时允许文档中的其他字段,请使用虚线表示法,例如
const query = { "fullDocument.author": someUserId };并像这样匹配:
{$match: query }https://stackoverflow.com/questions/63911277
复制相似问题