为什么update()完全覆盖Firebase中的数据? set()与update() [英] Why does update() completely overwrites my data in Firebase? set() vs. update()

查看:67
本文介绍了为什么update()完全覆盖Firebase中的数据? set()与update()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了Firebase文档,此外,我还发现了一些有关Firebase中set()与update()的stackoverflow主题:例如

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.

在下面的代码中,为什么update()会覆盖我现有的数据?

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

我最初有一个标题,内容,datePosted和Id,当我对其进行更新时,标题和内容将被更新,而dataPosted和Id将被删除.为什么?虽然这应该是set()的行为?

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

推荐答案

update()的工作方式是,它仅查看您调用update的位置的直接子级.该位置下方的所有内容都会被替换.因此,您要做的就是每次都替换整个postId-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.

如果您只想更新postId-1的子代,则将其称为调用update()的基本位置:

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)

这篇关于为什么update()完全覆盖Firebase中的数据? set()与update()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆