简体   繁体   中英

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

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()?

前 后

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)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM