![](/img/trans.png)
[英]How to check which document is deleted on Firestore in Java - Android Studio
[英]Firestore - Check if the document which is being updated exists
據我所知 - 為了檢查document
是否存在,我應該使用get
函數並查看它是否存在。
我的問題是關於在更新時檢查 - 有可能嗎? (考慮到更新發生時document
可能會消失)。
我試圖更新一個空document
,但收到一個錯誤消息,指出該文檔不存在,但我認為這可能不是檢查此問題的成功方法。
將數據寫入 Cloud Firestore 的方法有以下幾種:
SetOptions.merge()
。set()
但如果文檔已經存在則失敗。 所以你只需要為你的用例使用正確的操作。 如果您想在不知道文檔是否存在的情況下更新文檔,您可以像這樣使用set()
和merge()
選項(此示例適用於 Java):
// Update one field, creating the document if it does not already exist.
Map<String, Object> data = new HashMap<>();
data.put("capital", true);
db.collection("cities").document("BJ")
.set(data, SetOptions.merge());
如果您只想在文檔存在的情況下執行更新,那么使用update
就是正確的做法。 您觀察到的行為是您可以信賴的行為。
我們專門設計了這一點,以便可以執行文檔的部分更新,而不會創建您的代碼不准備處理的不完整文檔。
我們可以使用 update 並將掩碼參數設置為 true,如下所示:-
firestore.updateDocument("GFrom/"+data.email,data, true);
嘗試更新不存在的文檔的最簡單方法是:
try {
await db.collection('cities').doc('BJ').update('key', 'value')
} catch (error) {
// document not exists, do nothing
}
我認為在這種類型的場景中set()和merge: true是最好的選擇。 使用顫振
firestoreInstance.collection("users").doc(firebaseUser.uid).set(
{
"username" : "userX",
},SetOptions(merge: true))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.