dimanche 4 août 2019

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 isnt 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..

Aucun commentaire:

Enregistrer un commentaire