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/