Firebase Firestore transaction “Transaction failed

2020-03-31 10:51发布

All of my firestore transactions fail when I want to get document.

I've tried getting other files changed rules to be public. I've found out that when i use if checking it seems like get function returned data.

val currentUserDocument = firebaseFirestore.collection("user").document(firebaseAuth.currentUser!!.uid)
val classMemberDocument = firebaseFirestore.collection("class").document(remoteClassID).collection("member").document(firebaseAuth.currentUser!!.uid)

        firebaseFirestore.runTransaction { transaction ->
            val userSnapshot = transaction.get(currentUserDocument)

            val isInClass = userSnapshot.getBoolean("haveRemoteClass")!!
            val classID = userSnapshot.getString("remoteClassID")!!

            if (isInClass == true && classID == remoteClassID) {
                transaction.update(currentUserDocument, "haveRemoteClass", false)
                transaction.update(currentUserDocument, "remoteClassID", "")

                transaction.delete(classMemberDocument)
            } else {
                throw FirebaseFirestoreException("You aren't in this class!", FirebaseFirestoreException.Code.ABORTED)
            }

            null
        }

1条回答
Animai°情兽
2楼-- · 2020-03-31 11:22

This typically means that the data that you're using in the transaction is seeing a lot of contention.

Each time you run a transaction, Firebase determines the current state of all documents you use in the transaction, and sends that state and the new state of those documents to the server. If the documents that you got were changed between when the transaction started and when the server gets it, it rejects the transaction and the client retries.

For the client to fail like this, it has to retry more often than is reasonable. Consider reducing the scope of your transaction to cover fewer documents, or find another way to reduce contention (such as the approach outlined for distributed counters).

查看更多
登录 后发表回答