1

Let's say I have this data on my 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
    }
  }
}

How would I search by uid and get that result's snapshot?

Here's what I have tried:

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

Which returns: accounts matching UID of github:123456789 null despite having the uid inside that data of /player/...

Zeng Cheng
  • 755
  • 2
  • 7
  • 16

2 Answers2

4

Order by the child you want to filter on and then filter:

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

Since you only expect a single player, you can probably get by with once('child_added'. If you need to handle potentially multiple players with the same uid, then:

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

Or

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

I am with Chrillewoodz on the structure though: I would always expect to see the uid as the key for a collection of users. You could search for the name with the approach above in that case.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

Remember, everything in Firebase is an url. So you can just do this to get the data you want:

'https://mygame.firebaseio.com/player/' + uid
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • Yes but they aren't stored as UIDs but rather player usernames – Zeng Cheng Jul 11 '15 at 21:46
  • @DanF Why don't you store the username under the uid instad of the opposite? Since the uid is always unique this is a better option than storing the keys as player names. – Chrillewoodz Jul 11 '15 at 21:47
  • 2
    @Chrilliewoodz I suppose but then I wouldn't know how to search for usernames... in the database. – Zeng Cheng Jul 11 '15 at 23:00