javascript - 为什么 update() 会完全覆盖我在 Firebase 中的数据? set() 与 update()

标签 javascript firebase firebase-realtime-database

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

很明显他们两个之间有什么区别。

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

我最初有标题、内容、发布日期和 ID,当我更新它时,标题和内容会更新,数据发布和 ID 会被删除。为什么?虽然这应该是 set() 的行为?

before after

最佳答案

update() 的工作方式是它只查看调用 update 的位置的直接子级。该位置下方的所有内容都将被替换。因此,您所做的就是每次替换整个 postId-1。

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

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

关于javascript - 为什么 update() 会完全覆盖我在 Firebase 中的数据? set() 与 update(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53458434/

相关文章:

javascript - 将纯文本呈现为 HTML 维护空白——没有 <pre>

javascript - 从ajax驱动的网站检索渲染的html

javascript - 访问 firebase 数据库中的数据

swift - 从 App Delegate 执行 Segue - Swift

javascript - 不在 forEach 语句中推送元素

java - 如何在 Android 上仅更新 Firebase 数据库上的特定字段

javascript - WebExtensions 中的 browser.alarms.create 与 setTimeout/setInterval 有何区别?

javascript - 通过 'paper-item' 更新 'paper-listbox' 内的 'dom-repeat',数据绑定(bind)失败

javascript - 从 documentSnapshot 获取 Cloud Firestore 文档引用

java - Redis 客户端阻止 Java 中的 firebase 监听器