java - 事务中读取的每个文档也必须写入 : Firestore Transaction Exception in android

标签 java android firebase google-cloud-firestore

Firestore 事务给我以下错误:

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

这是一段代码:

   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 条件:if(documentSnapshot1.exists() && documentSnapshot2.exists()) 那么事务将成功完成并且不会出现错误。

但是设置此事务的要点是 if 条件。请帮忙。

最佳答案

代码中的问题在于,在交易中您正在阅读两个文档:

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

但你永远不会回信。正如我在您的代码中看到的,您只需要它们进行删除操作,因此在这种情况下,在事务之前而不是在事务内部读取它们,您的问题将得到解决。

关于java - 事务中读取的每个文档也必须写入 : Firestore Transaction Exception in android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154998/

相关文章:

java - SpringBoot @WebMvcTest 安全问题

android - 谁在 mvp android 中调用 db 查询和 http get

Angular/Firebase - Guard 在 Firebase 初始化完成之前运行

java - 在 Android 中阻止短信

ios - iOS 14 上的 flutter FCM 7

java - Angular 火 : How to perform some operations on data before updating template

java - 使用 javax.swing.JOptionPane 作为输入时出现计算错误

java - 使用 found 通过 SSL 连接到 elasticsearch

java - 与java相比,c中的openssl摘要不同

java - 线程因未捕获的异常而退出(组 = 0x40015560)