简体   繁体   English

为什么 update() 会完全覆盖我在 Firebase 中的数据? 设置()与更新()

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

I have went through Firebase doc, plus I have found a few topics on stackoverflow about set() vs. update() in Firebase: eg here我已经浏览了 Firebase 文档,另外我在 stackoverflow 上找到了一些关于 Firebase 中的 set() 与 update() 的主题:例如这里

It is very clear what is the difference between the two of them.很清楚他们两个有什么区别。

In the following code, why does update() overwrites my existing data?在下面的代码中,为什么 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);
}

I originally have a title, content, datePosted and Id and when I update it the title and content gets updated and dataPosted and Id gets deleted.我最初有一个标题、内容、datePosted 和 Id,当我更新它时,标题和内容会更新,而 dataPosted 和 Id 会被删除。 Why?为什么? While this should be the behavior of set()?虽然这应该是 set() 的行为?

前 后

The way update() works is that it only looks at the immediate children of the location where you called update. update()的工作方式是仅查看调用update的位置的直接子代。 Everything underneath that location is replaced. 该位置下方的所有内容都会被替换。 So, what you're doing is replacing the entirety of postId-1 every time. 因此,您要做的是每次都替换整个postId-1。

If you only really want to update the children of postId-1, then make that the base location where you call update(): 如果您只想更新postId-1的子代,则将其作为调用update()的基本位置:

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

Following works for me:以下对我有用:

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

Aparently if I were to use it like the following it doesnt work (it overwrites:显然,如果我像下面这样使用它,它就不起作用(它会覆盖:

            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