gpt4 book ai didi

firebase - Firestore 事务多次触发导致错误数据

转载 作者:行者123 更新时间:2023-12-05 00:13:23 25 4
gpt4 key购买 nike

所以我有一个云功能,每次喜欢/不喜欢交易时都会触发它。此函数增加/减少 likesCount。我已经使用 Firestore 交易来实现相同的目标。我认为问题是事务 block 内的代码被多次执行,根据文档,这可能是正确的。

但我的点赞数在某些时候更新不正确。

 return firestore.runTransaction(function (transaction) {
return transaction.get(transRef).then(function (transDoc) {
let currentLikesCount = transDoc.get("likesCount");
if (event.data && !event.data.previous) {
newLikesCount = currentLikesCount == 0 || isNaN(currentLikesCount) ? 1 : transDoc.get("likesCount") + 1;
} else {
newLikesCount = currentLikesCount == 0 || isNaN(currentLikesCount) ? 0 : transDoc.get("likesCount") - 1;
}
transaction.update(transRef, { likesCount: newLikesCount });
});
});

有类似经历的人

最佳答案

伙计们终于找到了这种意外行为的原因。

如果您的应用程序将是流量密集型的,那么 Firestore 不适合维护计数器。他们在文档中提到了这一点。他们建议的解决方案是使用分布式计数器。

Many realtime apps have documents that act as counters. For example, you might count 'likes' on a post, or 'favorites' of a specific item.

In Cloud Firestore, you can only update a single document about once per second, which might be too low for some high-traffic applications.

https://cloud.google.com/firestore/docs/solutions/counters

我不相信这种方法,因为它对于一个简单的用例来说太复杂了,我偶然发现了以下博客

https://medium.com/evenbit/on-collision-course-with-cloud-firestore-7af26242bc2d

这些家伙结合使用 Firestore + Firebase,从而消除了他们的弱点。

Cloud Firestore is sitting conveniently close to the Firebase Realtime Database, and the two are easily available to use, mix and match within an application. You can freely choose to store data in both places for your project, if that serves your needs.

So, why not use the Realtime database for one of its strengths: to manage fast data streams from distributed clients. Which is the one problem that arises when trying to aggregate and count data in the Firestore.

说 Firestore 是对实时数据库的升级(正如它所宣传的那样)是不正确的,但它是具有不同目的的不同数据库,两者可以而且应该在大型应用程序中共存。这是我的想法。

关于firebase - Firestore 事务多次触发导致错误数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759969/

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