【问题标题】:Increment existing value in firebase firestore增加 Firebase Firestore 中的现有值
【发布时间】:2019-08-08 21:11:59
【问题描述】:

有没有办法增加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 函数可用于递增或递减数值字段值

5.9.0 版 - 2019 年 3 月 14 日

新增 FieldValue.increment(),可用于 update() 和 set(..., {merge:true}) 增加或减少数字字段值 安全无交易。

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

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

【问题讨论】:

  • Android SDK 获得相同的FieldValue.increment() 功能只是时间问题。
  • @DougStevenson 我希望 firebasae 团队在下一个版本中为 android 提供这种类型的功能......
  • @DougStevenson 是的!我使用了这个功能并在这里写了一个答案:stackoverflow.com/a/55548224/6086782 :)
  • @varun 感谢您指出更新信息
  • @varun 已投票

标签: java android firebase google-cloud-firestore


【解决方案1】:

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

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

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

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

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

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

注意:增量操作对于实现计数器很有用,但是 请记住,您每次只能更新一个文档一次 第二。如果您需要更新您的计数器高于此速率,请参阅 Distributed counters页面。


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

【讨论】:

  • .doc().document()有区别吗?
  • @ColinRicardo 没有区别
  • document函数用于获取java和kotlin中文档的引用
  • 工作得很好,但是当 Firestore 持久性打开时我遇到了一个问题。有什么解决办法吗?
猜你喜欢
  • 2020-07-26
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2020-02-06
  • 2020-07-11
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多