Firebase -按值搜索子节点

Firebase - Search a child by value

本文关键字:搜索 子节点 Firebase      更新时间:2023-09-26

假设我的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,尽管/player/的数据中有uid

按要筛选的子元素排序,然后再筛选:

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

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

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