【问题标题】:How To Put If Statement Inside Transaction Firebase Firestore如何将 If 语句放入事务 Firebase Firestore
【发布时间】:2019-08-04 08:41:32
【问题描述】:

当用户单击一个按钮时,它会检查 Firestore 中的文档是否存在,如果存在,则只需更新(增加)某个值,如果不使用新值创建新文档。

我可以做正常的documentRef.get() 和documentRef.set(),但是当我用 2 个用户同时按下按钮进行测试时。它只是把其中之一的新价值。所以我使用了事务。

在这个交易中,首先我得到了文档快照,然后我得到了价值。 然后我放 if 语句来检查文档是否存在,第一个语句存在文档工作正常,但是当我删除文档时,else 语句没有做任何事情。

是否可以在 Firebase Firestore 事务中使用 if 语句?

Map<String, Object> newDocumentSet = new HashMap<>();
        newDocumentSet.put("sold", 1);
        newDocumentSet.put("price", myProductPrice);

mDb.runTransaction(new Transaction.Function<Void>() {

            @Nullable
            @Override
            public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {

                DocumentSnapshot myDocumentSnapshot = transaction.get(myDocumentRef);
                long newAddSold = myDocumentSnapshot.getLong("sold") + 1;
                long newAddPrice = myDocumentSnapshot.getLong("price") + myProductPrice;

                if(myDocumentSnapshot.exists()){

                    transaction.update(myDocumentRef, "sold", newAddSold);
                    transaction.update(myDocumentRef, "price", newAddPrice);

                }else {

                    transaction.set(myDocumentRef, newDocumentSet);

                }


                return null;
            }
        });

我知道发生了什么,它没有显示任何错误,如果我犯了错误,或者有其他方法可以告诉我。

【问题讨论】:

    标签: java android firebase transactions google-cloud-firestore


    【解决方案1】:

    或者还有其他方法可以做到这一点..

    是的,甚至是一个更简单的,实际上比事务更有效,因为它不需要客户端和 Firebase 服务器之间的往返。假设mDb 指向正确的文档,要将sold 属性增加1,请使用以下代码行:

    mDb.update("sold", FieldValue.increment(1));
    

    【讨论】:

    • 但是如果有很多用户怎么办,那不是什么交易吗?即使可以,当文档不存在时创建文档是否有效?
    • 事务是在你需要先从服务器读取数据然后更改它时使用的。对于简单的增量操作,不需要事务。这就是 Firebase 实施此选项的原因。不管你有多少用户,这个解决方案都可以正常工作。
    【解决方案2】:

    您只需要从runTransaction 函数返回一个Map&lt;String, dynamic&gt; 值,并在运行事务中确保返回一个类似的映射值

    if (a) {
      return "value":true
    } else {
      return "value":false
    }
    

    然后在函数的返回语句中分配mapDynamic["value"];。然后你现在将执行你的代码的哪一部分。 mapDynamic 只是一个变量名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 2017-01-15
      • 2013-03-25
      • 2015-08-18
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      相关资源
      最近更新 更多