Firebase DB - 如何更新 Firebase 数据库中子项的特定值 [英] Firebase DB - How to update particular value of child in Firebase Database

查看:26
本文介绍了Firebase DB - 如何更新 Firebase 数据库中子项的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下面的代码中更新我的显示名称.如何更新 displayName?

我的数据库结构是:

<前>-用户-KUanJA9egwmPsJCxXpv显示名称:测试培训师"电子邮件:test@gmail.com"uid: "jRXMsNZHR2exqifnR2rXcceEMxF2"

解决方案

如果你想更新这个用户的 displayName:

var db = firebase.database();db.ref("-Users/-KUanJA9egwmPsJCxXpv/displayName").set("New trainer");

或者,您也可以通过以下方式获得相同的结果:

db.ref("-Users/-KUanJA9egwmPsJCxXpv").update({ displayName: "New trainer" });

但您可能不知道用户的 ID,在这种情况下,您需要先查找:

var query = db.ref("-Users").orderByChild("uid").equalTo("jRXMsNZHR2exqifnR2rXcceEMxF2");query.once(child_ added",函数(快照){snapshot.ref.update({ displayName: "New trainer" })});

关于您的数据结构的最后一句话:您似乎在存储用户配置文件,但您将它们存储在推送 ID 下.对于这种类型的结构,我们通常建议您将每个用户存储在其唯一 ID 下:

-用户jRXMsNZHR2exqifnR2rXcceEMxF2displayName:测试培训师"电子邮件:test@gmail.com"

使用这样的结构,您可以消除将同一用户存储两次的任何机会.此外,您现在无需查询即可更新用户的显示名称:

var currentUser = firebase.auth().currentUser;db.ref("-Users/"+currentUser.uid).update({ displayName: "New trainer" });

I want to update my display name in the code below. How can I update displayName?

My database structure is:

-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" });

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").orderByChild("uid").equalTo("jRXMsNZHR2exqifnR2rXcceEMxF2");
query.once("child_added", function(snapshot) {
  snapshot.ref.update({ displayName: "New trainer" })
});

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 Unique ID:

-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 DB - 如何更新 Firebase 数据库中子项的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆