Firebase 更新与设置

正如标题所说,我不能得到 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做完全相同的事情。

问候你, 很好

84489 次浏览

Atomicity

One big difference between the two samples you've given is in the number of write operations they send to the Firebase servers.

In the first case, you're sending a single update() command. That entire command will either succeed or fail. For example: if the user has permission to post to /user-posts/' + uid, but doesn't have permission to post to /posts, the entire operation will fail.

In the second case, you're sending two separate commands. With the same permissions, the write to /user-posts/' + uid will now succeed, while the write to /posts will fail.

Partial update vs complete overwrite

Another difference is not immediately visible in this example. But say that you're updating the title and body of an existing post, instead of writing a new post.

If you'd use this code:

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

You'd be replacing the entire existing post. So the original uid, author and starCount fields would be gone and there'll just be the new title and body.

If on the other hand you use an update:

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

After executing this code, the original uid, author and starCount will still be there as well as the updated title and body.