Lee*_*Lee 7 javascript crud firebase es6-promise firebase-realtime-database
我正在使用 Firebase 和 Node。
如果由于某种原因它不存在,我想使用相同的方法来更新对象或创建它。
考虑以下方法
const firebaseSave = async function(data) {
const uid = firebase.auth().currentUser.uid
const profilePath = `users/${uid}`
const profileData = {
name: data.name,
}
const userRef = firebaseDb.child(profilePath)
await userRef.set(profileData)
}
Run Code Online (Sandbox Code Playgroud)
确定是否应调用 update 或 set 的最佳和正确方法是什么?
谢谢
小智 5
基本上与:
“设置”您将数据写入或替换到定义的路径,例如 messages/users/
,您可以更新信息或创建信息。
看看这个:https: //firebase.google.com/docs/database/admin/save-data
我会说获取数据,检查是否有东西,如果没有默认为空对象 - 然后更新该对象。
就像是:
const valueSnapshot = await userRef.once('value');
const userValue = valueShapshot.exists() ? valueShapshot.val() : {};
const profileData = { ...userValue, name: data.name };
await userRef.set(profileData);
Run Code Online (Sandbox Code Playgroud)
也就是说,假设您希望保留现有数据,并将任何新数据合并到其中。如果您不关心覆盖任何内容,则根本不需要检查。
| 归档时间: |
|
| 查看次数: |
5919 次 |
| 最近记录: |