Firebase - 按值搜索子项

时间:2015-07-11 20:54:56

标签: javascript json firebase

假设我在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,但<{1}}会返回/player/

2 个答案:

答案 0 :(得分:4)

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

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作为用户集合的关键。在这种情况下,您可以使用上述方法搜索名称。

答案 1 :(得分:1)

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

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