Every document read in a transaction must also be written : Firestore Transaction Exception in android

五迷三道 提交于 2020-01-30 11:26:25

问题


Firestore Transactions is giving me the following error :

Caused by: com.google.firebase.firestore.FirebaseFirestoreException: Every document read in a transaction must also be written.

Here's the piece of code:

   db.runTransaction(new Transaction.Function<Void>() {
        @Override
        public Void apply(Transaction transaction) throws FirebaseFirestoreException {


            DocumentReference docRef2 = db.collection("ABC").document(mMatchedUserId);

            DocumentReference ref3 = db.collection("XYZ").document(mCurrentUserId);
            DocumentReference ref4 = db.collection("XYZ").document(mMatchedUserId);


            DocumentSnapshot documentSnapshot2 = transaction.get(docRef2);

            if(documentSnapshot2.exists())
            {
                transaction.delete(docRef2);
                transaction.set(ref3, myMap1);
                transaction.set(ref4,myMap2);
            }

            return null;
        }
    }).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "Transaction success!");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Transaction failure.", e);
        }
    });

If I remove this if condition :if(documentSnapshot1.exists() && documentSnapshot2.exists()) then the transaction completes successfully and there is no error.

But the major point of setting up this transaction was the if condition. Kindly help.


回答1:


The problem in your code lies in the fact that inside your transaction you are reading two documents:

DocumentSnapshot documentSnapshot1 = transaction.get(docRef1);
DocumentSnapshot documentSnapshot2 = transaction.get(docRef2);

But you never write them back. As I see in your code, you only need them to a delete operation so in such case, read them before the transaction rather than inside the transaction and your problem will be solved.



来源:https://stackoverflow.com/questions/58154998/every-document-read-in-a-transaction-must-also-be-written-firestore-transactio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!