簡體   English   中英

為什么 update() 會完全覆蓋我在 Firebase 中的數據? 設置()與更新()

[英]Why does update() completely overwrites my data in Firebase? set() vs. update()

我已經瀏覽了 Firebase 文檔,另外我在 stackoverflow 上找到了一些關於 Firebase 中的 set() 與 update() 的主題:例如這里

很清楚他們兩個有什么區別。

在下面的代碼中,為什么 update() 會覆蓋我現有的數據?

function saveChanges(event) {
    event.preventDefault();
    let modifiedTitle = document.getElementById('blog-title').value;
    let modifiedContent = document.getElementById('blog-content').value;
    let modifiedId = document.getElementById('blog-id-storage').innerHTML;
    let postData = 
        title: modifiedTitle,
        content: modifiedContent
    };
    let updates = {};
    updates[modifiedId] = postData;
    firebase.database().ref().child('posts/').update(updates);
}

我最初有一個標題、內容、datePosted 和 Id,當我更新它時,標題和內容會更新,而 dataPosted 和 Id 會被刪除。 為什么? 雖然這應該是 set() 的行為?

前 后

update()的工作方式是僅查看調用update的位置的直接子代。 該位置下方的所有內容都會被替換。 因此,您要做的是每次都替換整個postId-1。

如果您只想更新postId-1的子代,則將其作為調用update()的基本位置:

firebase.database().ref().child('posts').child(modifiedId)
    .update(postDate)

以下對我有用:

admin.database().ref(SITE).child("ChildName").child("2ndLevelChild")
    .update({[KeyVariable]:valueVariable});

顯然,如果我像下面這樣使用它,它就不起作用(它會覆蓋:

            var newChild = {};
            newChild["ChildName/" + "2ndLevelChild"] = {
              [KeyVariable]: valueVariable
            };

           admin.database().ref(SITE).update(newChild);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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