Firebase数据列表 [英] firebase List of Data

查看:107
本文介绍了Firebase数据列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我玩的在线浏览器游戏制作朋友列表扩展。每个用户都有一个朋友的列表。我试图找出添加新朋友时更新此列表的最佳方法。现在我把他们的朋友作为一个字符串,添加一个冒号,然后是新的朋友的名字,然后设置新的字符串作为他们的朋友字符串。我觉得有一个更好的办法,因为这看起来不正确:Friend0:Friend1:Friend2



这个过程的代码如下所示:

  var reqName = $('#addFriendText').val (); //要添加的名称
var name = args ['name']; //当前用户名
firebase.database()。ref('/ users /'+ name).once('value')。then(function(snapshot){
var friends = snapshot.val ()['friends']; //获取朋友字符串
newFriends = friends +':'+ reqName; //创建新朋友字符串
var dbRef = firebase.database()。ref('users ');
var obj = {};
obj [name] = {'friends':newFriends};
dbRef.update(obj).then(function(){// Store新朋友字符串
console.log('db updated');
});
});

有没有更干净的方法来做我想做的事?我听说数组不是最优的,但我需要某种列表结构。作为参考,我的控制台中的数据结构如下所示:




 <$ c解决方案

这取决于你想如何检索它们,一个更好的方法是: $ c $>users:{
Cap:{
friends:{
user1:true,
user2:true
}


$ / code $ / pre
$ b $ p建议您阅读这个


I'm making a friends list extension for an online browser game I play. Every user has a list of friends. I'm trying to figure out the best way to update this list when a new friend is added. Right now I get their friends as a string, add a colon followed by the new friends name, then set the new string back as their friends string. I feel however there is a better way to do so, as this doesn't look right: "Friend0:Friend1:Friend2"

My code for this process looks like this:

var reqName = $('#addFriendText').val();  // Name to be added
var name = args['name'];                  // Current users name
firebase.database().ref('/users/' + name).once('value').then(function(snapshot) {
   var friends = snapshot.val()['friends'];  // Get friends string
   newFriends = friends + ':' + reqName;     // Make new friends string
   var dbRef = firebase.database().ref('users');
   var obj = {};
   obj[name] = {'friends':newFriends};       
   dbRef.update(obj).then(function(){        // Store new friends string
       console.log('db updated');
   });
});

Is there a cleaner way to do what I'm trying to do? I heard arrays aren't optimal but I need some sort of list structure. For reference, the data structure looks like this in my console:

解决方案

It depends on how you want to retrieve them, a better approach would be this:

"users": {
  "Cap": {
    "friends": {
      "user1": true,
      "user2": true
    }
  }
}

I suggest reading this

这篇关于Firebase数据列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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