代码之家  ›  专栏  ›  技术社区  ›  Ashvin solanki

FielBaseFieldSt店中增加现有值

  •  0
  • Ashvin solanki  · 技术社区  · 6 年前

    是否有任何方法来增加现有值 firestore ?

    What i am trying

        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日

    Added FieldValue.increment(),可用于update()和 将(…,{merge:true})设置为递增或递减数值字段值 安全无交易。

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


    因此,我的Questuy是在FixSt店Android中增加现有值的函数吗?


    0 回复  |  直到 6 年前
        1
  •  2
  •   Ashvin solanki    5 年前

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

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

    用法如下(从官方文件来看,仅此而已):

    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'

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


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

    推荐文章