gpt4 book ai didi

angularjs - 在 Firebase 中增加所有值的最有效方法

转载 作者:行者123 更新时间:2023-12-04 13:37:50 24 4
gpt4 key购买 nike

假设我有这样的条目:

Firebase Image

我想增加 priority估计列表中的每个项目的字段为 1。

我可以得到这样的估计:

var estimates = firebase.child('Estimates');

之后我将如何自动将每个估计优先级增加 1?

最佳答案

仅适用于 FIRSTORE API,不适用于 FIREBASE

感谢最新的 Firestore 补丁(2019 年 3 月 13 日),您无需遵循上述其他答案。

Firestore 的 FieldValue 类现在托管一个 增量 以原子方式更新 firestore 数据库中数字文档字段的方法。您可以将此 FieldValue 标记与 set 一起使用(合并选项为真)或 update DocumentReference 的方法目的。

用法如下(来自官方 docs ,仅此而已):

DocumentReference washingtonRef = db.collection("cities").document("DC");

// Atomically increment the population of the city by 50.
washingtonRef.update("population", FieldValue.increment(50));

如果您想知道,它可以从版本 18.2.0 获得。的消防站。为方便起见,Gradle 依赖项配置为 implementation 'com.google.firebase:firebase-firestore:18.2.0'

Note: Increment operations are useful for implementing counters, but keep in mind that you can update a single document only once per second. If you need to update your counter above this rate, see the Distributed counters page.



编辑 1 : FieldValue.increment()纯粹是“服务器”端(发生在 Firestore 中),因此您不需要将当前值公开给客户端。

编辑 2 :在使用管理 API 时,您可以使用 admin.firestore.FieldValue.increment(1)对于相同的功能。感谢 @Jabir Ishaq 自愿让我知道未记录的功能。 :)

编辑 3 :如果要增减的目标字段不是数字或不存在,则 increment方法将值设置为当前值!这在您第一次创建文档时很有帮助。

关于angularjs - 在 Firebase 中增加所有值的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34458930/

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