【发布时间】:2019-08-04 08:41:32
【问题描述】:
当用户单击一个按钮时,它会检查 Firestore 中的文档是否存在,如果存在,则只需更新(增加)某个值,如果不使用新值创建新文档。
我可以做正常的documentRef.get() 和documentRef.set(),但是当我用 2 个用户同时按下按钮进行测试时。它只是把其中之一的新价值。所以我使用了事务。
在这个交易中,首先我得到了文档快照,然后我得到了价值。 然后我放 if 语句来检查文档是否存在,第一个语句存在文档工作正常,但是当我删除文档时,else 语句没有做任何事情。
是否可以在 Firebase Firestore 事务中使用 if 语句?
Map<String, Object> newDocumentSet = new HashMap<>();
newDocumentSet.put("sold", 1);
newDocumentSet.put("price", myProductPrice);
mDb.runTransaction(new Transaction.Function<Void>() {
@Nullable
@Override
public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot myDocumentSnapshot = transaction.get(myDocumentRef);
long newAddSold = myDocumentSnapshot.getLong("sold") + 1;
long newAddPrice = myDocumentSnapshot.getLong("price") + myProductPrice;
if(myDocumentSnapshot.exists()){
transaction.update(myDocumentRef, "sold", newAddSold);
transaction.update(myDocumentRef, "price", newAddPrice);
}else {
transaction.set(myDocumentRef, newDocumentSet);
}
return null;
}
});
我知道发生了什么,它没有显示任何错误,如果我犯了错误,或者有其他方法可以告诉我。
【问题讨论】:
标签: java android firebase transactions google-cloud-firestore