Firestore中同时更新单个文档的更新

huangapple go评论65阅读模式
英文:

Updates on a single document at the same time in Firestore

问题

以下是您要翻译的内容:

"Structure:"

假设我有一个应用程序,两个用户彼此对战。一个游戏包含多个回合,两名玩家可以同时进行。每个游戏在Firestore中表示为一个文档,其中存储了所有回合。为了简单起见,假设回合仅包含两个字段,player1Time和player2Time。当玩家完成他们的回合时,将触发云函数,该函数会更新他们的时间(取决于玩家是player1还是player2)。此外,还有一个名为state的字段(类型为数字),需要在每次玩家完成他们的回合时增加(每轮两次):

"Question:"

由于两名玩家可以同时进行一轮,有可能在相同时间应用于文档的写操作。这些写操作不会“冲突”,因为它们写入文档中的不同字段(player1Time或player2Time,它们都存储在同一个数组中),并且使用admin.firestore.FieldValue.increment更新字段state。不将此逻辑写为事务是否会出现问题?

英文:

I was wondering if the following functionality would require to be implemented as a transaction in Firestore:

Structure:

Assume that I have an application where two users play against each other. One game contains multiple rounds, which both players can play at the same time. Each game is represented as one document in Firestore, within this document all the rounds are stored. For the sake of simplicity, assume that the rounds only consist of two fields, player1Time, and player2Time. After a player finished their round, a cloud function is triggered which updates their time (depending on the player being player1 or player2). Additionally, there is a field called state (type number) that needs to be increased every time a player finishes their round (twice per round):

Question:

Since both players can play a round at the same time, there is a chance that a write operation to a document is applied at the same time. These write operations do not "collide" because they write to different fields within that document (either player1Time or player2Time, which are both stored in the same array), and the field state is updated by using admin.firestore.FieldValue.increment. Would there be any problems with not writing this logic as a transaction?

答案1

得分: 1

此外,还有一个名为“state”的字段(类型为数字),需要在每次玩家完成他们的回合时增加(每轮两次)。

既然你说有可能两个用户同时完成游戏,但要更新不同的字段,那么你不需要使用事务。

另一方面,你正在使用的增量操作会原子地增加“state”字段。事务和增量操作之间的区别在于后者在执行更新时不会读取字段的值。

因此,在你的用例中,不需要使用任何事务。

英文:

> Additionally, there is a field called state (type number) that needs to be increased every time a player finishes their round (twice per round).

Since you say that there may be a chance that both users can finish the game at the exact same time, but you update different fields, then you don't need to use a transaction.

On the other hand, the increment operation that you're using increments the state field atomically. The difference between a transaction and the increment operation is that the latter doesn't read the value of the field when it performs the update.

So in your use case, there is no need for any transactions.

huangapple
  • 本文由 发表于 2023年2月27日 15:17:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定