Firebase数据库 - 如何在Firebase数据库中更新孩子的特定值 [英] Firebase DB - How to update particular value of child in Firebase Database
问题描述
我想在下面的代码中更新我的显示名称。我如何更新我的显示名称。
我的数据库结构如下:
I want to update my display name in below code. How can I update my displayName. My database structer is as below:
-Users
-KUanJA9egwmPsJCxXpv
displayName:"Test Trainer"
email:"test@gmail.com"
uid: "jRXMsNZHR2exqifnR2rXcceEMxF2"
推荐答案
如果您想更新此用户的显示名称:
If you want to update the displayName of this user:
var db = firebase.database();
db.ref("-Users/-KUanJA9egwmPsJCxXpv/displayName").set("New trainer");
或者,您也可以得到相同的结果:
Alternatively, you can also get the same with:
db.ref("-Users/-KUanJA9egwmPsJCxXpv").update({ displayName: "New trainer" });
但是,您可能不知道用户的ID,在这种情况下您需要查看首先:
But it's likely you don't know the ID of the user, in which case you need to look that up first:
var query db.ref("-Users").orderByKey("uid").equalTo("jRXMsNZHR2exqifnR2rXcceEMxF2");
query.once("child_added", function(snapshot) {
snapshot.ref.update({ displayName: "New trainer" })
});
对数据结构的最后一点评论是:您似乎在存储用户配置文件,但是将它们存储在一个推送ID下。对于这种类型的结构,我们通常建议您将每个用户存储在他们的UID下:
One final remark on your data structure though: you seem to be storing user profiles, but you're storing them under a push ID. For this type of structure we usually recommend that you store each user under their UID:
-Users
jRXMsNZHR2exqifnR2rXcceEMxF2
displayName:"Test Trainer"
email:"test@gmail.com"
有了这样的结构,你可以删除任何两次存储同一用户的机会。此外,您现在可以更新用户的显示名称而不需要查询:
With such a structure you remove any chance that you're storing the same user twice. Plus, you can now update the user's display name without needing a query:
var currentUser = firebase.auth().currentUser;
db.ref("-Users/"+currentUser.uid).update({ displayName: "New trainer" });
这篇关于Firebase数据库 - 如何在Firebase数据库中更新孩子的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!