gpt4 book ai didi

java - 增加 Firebase Firestore 中的现有值(value)

转载 作者:搜寻专家 更新时间:2023-11-01 09:21:13 26 4
gpt4 key购买 nike

有什么方法可以增加 firestore 中的现有值吗? ?

我正在尝试什么。
    FirebaseFirestore.getInstance()
.collection("notifications")
.document(response.getString("multicast_id"))
.set(notificationData);
FirebaseFirestore.getInstance()
.collection("users")
.document(post.userId)
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
int followers = Integer.valueOf(task.getResult().getData().get("followers").toString());
FirebaseFirestore.getInstance()
.collection("users")
.document(post.userId).update("followers", followers++).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
}
}
});
数据库结构
users

- data....
- followers(number)

根据这个Answer可用于递增或递减数字字段值的函数

Version 5.9.0 - Mar 14, 2019

Added FieldValue.increment(), which can be used in update() and set(..., {merge:true}) to increment or decrement numeric field values safely without transactions.

https://firebase.google.com/support/release-notes/js

是否有任何函数可用于增加 firestore android 中的现有值?

最佳答案

感谢最新的 Firestore 补丁(2019 年 3 月 13 日)

Firestore 的 FieldValue 类现在包含一个increment 方法,该方法以原子方式更新 firestore 数据库中的数字文档字段。您可以将此 FieldValue 标记与 DocumentReference 对象的 set(mergeOptions 为 true)或 update 方法一起使用。

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

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 版的 firestore 中获得。为了您的方便,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.


FieldValue.increment() 是纯粹的“服务器”端(发生在 firestore 中),因此您不需要向客户端公开当前值。

关于java - 增加 Firebase Firestore 中的现有值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55222414/

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