gpt4 book ai didi

node.js - Mongodb更改流运行多次(有点): Node app running multiple instances

转载 作者:太空宇宙 更新时间:2023-11-03 22:59:24 25 4
gpt4 key购买 nike

我的 Node 应用程序使用 Mongo 更改流,并且该应用程序在生产中运行 3 个以上实例(最终会更多,因此随着它的增长,这将成为一个更大的问题)。因此,当发生更改时,更改流功能会运行与流程一样多的次数。

如何设置以使更改流仅运行一次?

这是我得到的:

const options = { fullDocument: "updateLookup" };

const filter = [
{
$match: {
$and: [
{ "updateDescription.updatedFields.sites": { $exists: true } },
{ operationType: "update" }
]
}
}
];

const sitesStream = Client.watch(sitesFilter, options);

// Start listening to site stream
sitesStream.on("change", async change => {
console.log("in site change stream", change);
console.log(
"in site change stream, update desc",
change.updateDescription
);

// Do work...
console.log("site change stream done.");
return;
});

最佳答案

仅使用 Mongodb 查询运算符即可轻松完成。您可以在 ID 字段上添加模查询,其中除数是应用程序实例的数量 (N)。余数就是 {0, 1, 2, ..., N-1} 的元素。如果您的应用实例按从 0 到 N-1 的升序编号,您可以像这样编写过滤器:

const filter = [
{
"$match": {
"$and": [
// Other filters
{ "_id": { "$mod": [<number of instances>, <this instance's id>]}}
]
}
}
];

关于node.js - Mongodb更改流运行多次(有点): Node app running multiple instances,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com