Firebase update vs set

Firebase update vs set

本文关键字:set vs update Firebase      更新时间:2023-09-26

正如标题所说,我无法得到updateset之间的差异。此外,文档也不能帮助我,因为如果我使用set代替,那么更新示例的工作原理完全相同。

文档中的update示例:

function writeNewPost(uid, username, title, body) {
    var postData = {
        author: username,
        uid: uid,
        body: body,
        title: title,
        starCount: 0
    };
    var newPostKey = firebase.database().ref().child('posts').push().key;
    var updates = {};
    updates['/posts/' + newPostKey] = postData;
    updates['/user-posts/' + uid + '/' + newPostKey] = postData;
    return firebase.database().ref().update(updates);
}

使用set

的相同示例
function writeNewPost(uid, username, title, body) {
    var postData = {
        author: username,
        uid: uid,
        body: body,
        title: title,
        starCount: 0
    };
    var newPostKey = firebase.database().ref().child('posts').push().key;
    firebase.database().ref().child('/posts/' + newPostKey).set(postData);
    firebase.database().ref().child('/user-posts/' + uid + '/' + newPostKey).set(postData);
}

所以也许从文档的例子应该更新,因为现在看起来像updateset做完全相同的事情。

亲切的问候,野猪

原子性

您给出的两个示例之间的一个很大的区别是它们发送到Firebase服务器的写操作的数量。

在第一种情况下,您发送了一个update()命令。整个命令要么成功,要么失败。例如:如果用户有权限发送到/user-posts/' + uid,但没有权限发送到/posts,则整个操作将失败。

在第二种情况下,您发送两个单独的命令。在相同的权限下,对/user-posts/' + uid的写入将成功,而对/posts的写入将失败。

部分更新vs完全覆盖

在这个例子中,另一个区别不是立即可见的。但是,假设您正在更新现有文章的标题和正文,而不是编写新文章。

如果你想使用下面的代码:

firebase.database().ref().child('/posts/' + newPostKey)
        .set({ title: "New title", body: "This is the new body" });

你将取代整个现有的职位。因此,原来的uid, authorstarCount字段将消失,只剩下新的titlebody

另一方面,如果你使用update:

firebase.database().ref().child('/posts/' + newPostKey)
        .update({ title: "New title", body: "This is the new body" });

执行此代码后,原始的uid, authorstarCount将仍然存在,以及更新的titlebody