簡體   English   中英

Firestore - 檢查正在更新的文檔是否存在

[英]Firestore - Check if the document which is being updated exists

據我所知 - 為了檢查document是否存在,我應該使用get函數並查看它是否存在。

我的問題是關於在更新時檢查 - 有可能嗎? (考慮到更新發生時document可能會消失)。

我試圖更新一個空document ,但收到一個錯誤消息,指出該文檔不存在,但我認為這可能不是檢查此問題的成功方法。

將數據寫入 Cloud Firestore 的方法有以下幾種:

  • update() - 更改已存在文檔上的字段。 如果文檔不存在,則失敗。
  • set() - 覆蓋文檔中的數據,如果文檔不存在則創建該文檔。 如果您只想部分更新文檔,請使用SetOptions.merge()
  • create() - 僅在服務器端 SDK 中可用,類似於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM