Ben*_*ene 66 javascript firebase firebase-realtime-database
正如标题所说,我不能得到之间的区别update
和set
.此外,文档无法帮助我,因为如果我使用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)
所以,也许从文档的例子应该更新,因为现在看起来update
和set
做同样的事情.
亲切的问候,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
,author
和starCount
领域将消失,以后还有刚刚成为新的title
和body
.
另一方面,如果您使用更新:
firebase.database().ref().child('/posts/' + newPostKey)
.update({ title: "New title", body: "This is the new body" });
Run Code Online (Sandbox Code Playgroud)
执行此代码,原来后uid
,author
和starCount
依然存在以及更新title
和body
.
归档时间: |
|
查看次数: |
48298 次 |
最近记录: |