问题
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