Ad

How To Put If Statement Inside Transaction Firebase Firestore

When the user clicks a button it's going to check if the Document in Firestore is exists or not, if it is, then just update (increase) 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 which is document is exist is working fine, but when I deleted the document, the else statement didn't do anything.

Is it even possible to use if statement 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;
            }
        });

I don't know what's happening, it didn't show any error, please tell me if I made some mistake or there is another way of doing this.

Ad

Answer

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));
Ad
source: stackoverflow.com
Ad