Firebase update vs set
Firebase update vs set
正如标题所说,我无法得到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);
}
使用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);
}
所以也许从文档的例子应该更新,因为现在看起来像update
和set
做完全相同的事情。
亲切的问候,野猪
原子性
您给出的两个示例之间的一个很大的区别是它们发送到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
, author
和starCount
字段将消失,只剩下新的title
和body
。
另一方面,如果你使用update:
firebase.database().ref().child('/posts/' + newPostKey)
.update({ title: "New title", body: "This is the new body" });
执行此代码后,原始的uid
, author
和starCount
将仍然存在,以及更新的title
和body
。
相关文章:
- setInteval vs setTimeout
- $(this).prop('property') vs. this.property
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- Ember Data DS.Model's set函数不起作用
- Js.erb VS按钮标记-不'不起作用.为什么?
- reactjs this.refs vs document.getElementById
- C#asp.net mvc Set CheckBoxFor已检查的具有Model Value的属性
- 为什么JavaScript可以'找不到给定的InnerHTML并返回Cannot set property
- Performance: NaCl vs Emscripten
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- Advantages to DOMParser vs template & innerHTML
- JavaScript-===vs===运算符性能
- 无法在基于Cordova的应用程序中读取Set Cookie标头
- 开发第三方小部件-Angular vs jQuery vs普通的旧JS
- PhantomJS(vs nightwatch.js)设置cookie错误
- 在不兼容的接收器上调用的方法Set.prototype.add未定义
- ractivejs observe init vs set/push/update
- TypedArray Set vs. Unrolled Loop (Javascript)
- set / get VS setUTC / getUTC
- Firebase update vs set