Firebase更新与设置

Ben*_*ene 66 javascript firebase firebase-realtime-database

正如标题所说,我不能得到之间的区别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);
}
Run Code Online (Sandbox Code Playgroud)

使用相同的例子 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);
}
Run Code Online (Sandbox Code Playgroud)

所以,也许从文档的例子应该更新,因为现在看起来updateset做同样的事情.

亲切的问候,Bene

Fra*_*len 117

原子性

您给出的两个示例之间的一个重要区别在于它们发送到Firebase服务器的写入操作数.

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

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

部分更新与完全覆盖

在此示例中,不会立即看到另一个区别.但是说你正在更新现有帖子的标题和正文,而不是写一篇新帖子.

如果您使用此代码:

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

您将替换整个现有帖子.所以原来uid,authorstarCount领域将消失,以后还有刚刚成为新的titlebody.

另一方面,如果您使用更新:

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

执行此代码,原来后uid,authorstarCount依然存在以及更新titlebody.

  • 非常感谢您的回答.也许用更新方法的更清晰的示例来更新文档是个好主意. (7认同)
  • @ frank-van-puffelen听起来像`update()`是可以做到这一切的goto主力.甚至可以将`update`属性设置为`null` ...有效地执行`remove`的相同工作.那么,有没有真正合理的理由使用`set()`呢?也许你想要做一些严肃的修剪/重塑数据? (6认同)
  • 当然,需要对文档进行改进,以便以清晰的方式添加此答案中的信息. (5认同)
  • 是的,它确实。尝试一下,如果您在使其适用于您的案例时遇到问题,请提出一个新问题。 (3认同)
  • **更新**也可以用于创建新的数据字段@Frank吗? (2认同)