如何增加Cloud Firestore中的现有数字字段 [英] How to increment existing number field in Cloud Firestore
问题描述
我有一个字段,指示交易数量.交易发生后,我想将其增加1
.我找不到任何直接执行此方法的方法.
I have a field which indicates the number of transactions. I would like to increment it by 1
as soon as a transaction occurs. I could'nt find any method to directly execute this.
一种方法是先获取用户,然后使用接收到的值+ 1
更新该字段,但这太长且太慢.
One method is to get the user first and then update the field with the received value + 1
, but this is too lengthy and slow.
有人可以告诉我其他可行的方法吗?
Can anyone tell me any other feasible method?
推荐答案
Firestore现在为此指定了一个特定的运算符FieldValue.increment()
.通过将此运算符应用于字段,该字段的值可以作为服务器上的单个操作来递增(或递减).
Firestore now has a specific operator for this called FieldValue.increment()
. By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.
从Firebase文档上,在递增数值:
From the Firebase documentation on incrementing a numeric value:
var washingtonRef = db.collection('cities').doc('DC');
// Atomically increment the population of the city by 50.
washingtonRef.update({
population: firebase.firestore.FieldValue.increment(50)
});
因此,无论当前值是多少,此示例都会将总体增加50.如果该字段尚不存在(或不是数字),则在这种情况下将其设置为50
.
So this example increments the population by 50, no matter what is current value is. If the field doesn't exist yet (or is not a number), it is set to 50
in this case.
这篇关于如何增加Cloud Firestore中的现有数字字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!