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

◇◆丶佛笑我妖孽 提交于 2019-12-25 00:12:32

问题


I have went through Firebase doc, plus I have found a few topics on stackoverflow about set() vs. update() in Firebase: e.g.here

It is very clear what is the difference between the two of them.

In the following code, why does update() overwrites my existing data?

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. Why? While this should be the behavior of set()?


回答1:


The way update() works is that it only looks at the immediate children of the location where you called update. Everything underneath that location is replaced. So, what you're doing is replacing the entirety of postId-1 every time.

If you only really want to update the children of postId-1, then make that the base location where you call update():

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


来源:https://stackoverflow.com/questions/53458434/why-does-update-completely-overwrites-my-data-in-firebase-set-vs-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!