【问题标题】:Firebase - Search a child by valueFirebase - 按值搜索孩子
【发布时间】:2015-07-11 20:54:55
【问题描述】:

假设我的 Firebase 上有这些数据:

https://mygame.firebaseio.com/player

{
  "player": {
    "bloodgulf01": {
      "username": "bloodgulf01",
      "uid": "twitter:102032",
      "level": 2,
      "map": 3,
      "x": 51,
      "y": 12
    },
    "damjanovic": {
      "username": "damjanovic",
      "uid": "github:77371",
      "level": 5,
      "map": 2,
      "x": 21,
      "y": 44
    }
  }
}

我如何通过uid 搜索并获得snapshot 的结果?

这是我尝试过的:

new Firebase("https://mygame.firebaseio.com/player")
    .startAt(authData.uid)
    .endAt(authData.uid)
    .once('value', function(snap) {
       console.log('accounts matching UID of ' + authData.uid, snap.val())
    });

返回:accounts matching UID of github:123456789 null 尽管uid/player/ 的数据中...

【问题讨论】:

    标签: javascript json firebase


    【解决方案1】:

    按您要过滤的孩子排序,然后过滤:

    new Firebase("https://mygame.firebaseio.com/player")
      .orderByChild('uid')
      .equalTo(authData.uid)
      .once('child_added', function(snap) {
         console.log('account matching UID of ' + authData.uid, snap.val())
      });
    

    由于您只期望一个玩家,您可能可以使用once('child_added'。如果您需要处理可能具有相同 uid 的多个玩家,那么:

      .on('child_added', function(snap) {
         console.log('account matching UID of ' + authData.uid, snap.val())
      });
    

    或者

      .once('value', function(snap) {
         snap.forEach(function(child) {
           console.log('account matching UID of ' + authData.uid, child.val())
         });
      });
    

    我在结构上支持 Chrillewoodz:我总是希望将 uid 视为一组用户的关键。在这种情况下,您可以使用上述方法搜索名称。

    【讨论】:

      【解决方案2】:

      请记住,Firebase 中的所有内容都是 url。所以你可以这样做来获取你想要的数据:

      'https://mygame.firebaseio.com/player/' + uid
      

      【讨论】:

      • 是的,但它们不存储为 UID,而是存储为玩家用户名
      • @DanF 为什么不将用户名存储在对面的uid instad 下?由于 uid 始终是唯一的,因此这比将密钥存储为玩家名称更好。
      • @Chrilliewoodz 我想,但我不知道如何在数据库中搜索用户名......
      猜你喜欢
      • 2019-01-21
      • 2017-03-21
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多