简体   繁体   中英

How To Put If Statement Inside Transaction Firebase Firestore

When the user click a button its gonna check if the Document in Firestore is exists or not, if it is, then just update (increse) some value, and if it isn't create a new document with the new value.

I could just do the normal documentRef.get() , and documentRef.set() , but when I tested it with 2 user press the button at the same time. Its just put the new value of one of them. and so I used transaction.

In this transaction, first i get the documentsnapshot, and I get the value. and then I put if statement to check if the document is exist, the first statement wich is document is exist is working fine, but when i deleted the document, the else statement diddnt do anything.

Is it even possible to use if statment inside Firebase Firestore transaction?

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;
            }
        });

idk whats happening, it diddnt show any error, please tell me if i made some mistake or there is another way of doing this.

or there is another way of doing this..

Yes there is, even a simpler one which in fact is more efficient than a transaction because it does not require a round trip between the client and Firebase servers. Assuming that the mDb points to the correct document, to increment the sold property by 1 , please use the following line of code:

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

All you need is to return a Map<String, dynamic> value from the runTransaction function and inside the run transaction make sure you return a map value like

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

Then in the return statement of your function assign mapDynamic["value"]; . Then you will now which part of your code was executed. mapDynamic is just a variable name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM