交易中读取的每个文档也必须写入:Android中的Firestore交易异常

时间:2019-09-29 12:00:24

标签: java android firebase google-cloud-firestore

Firestore交易给我以下错误:

  

原因:com.google.firebase.firestore.FirebaseFirestoreException:必须写入在事务中读取的每个文档。

这是一段代码:

   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条件。请帮助。

1 个答案:

答案 0 :(得分:2)

代码中的问题在于,在事务内部您正在阅读两个文档:

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

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

相关问题