Mongo changeStream用于查找查询

问题描述

我想对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()时,它会起作用。

问题出在哪里? 谢谢。

编辑:我希望能够将query.find()的{​​{1}}重用。

解决方法

该示例中的$match阶段基本上是

{$match: { fullDocument: { author: someUserId }}}

如果fullDocument正好是{ author: someUserId }并且没有其他字段或值,则将仅匹配

为了在允许文档中其他字段匹配的同时匹配作者,请使用点分符号,例如

const query = { "fullDocument.author": someUserId };

并匹配:

{$match: query }