Roman Melnyk
Roman Melnyk

Reputation: 190

firebase orderbychild equalTo

Hi I'm building an app using firebase and here is my firebase model:

firebase model

Code for search user by name:

exports.findByUsername = function (username, cb) {

ref.orderByChild("username")
    .equalTo(username)
    .once("value", function (snapshot) {
        records = snapshot.val();

        if (records === null) {
            return cb(null, null); 
        }

        return cb(null, records);
    });

};

I expect to receive an object when I'm looking for the first user:

 [ 1 ,
  { clubID: 4,
    displayName: 'Jack',
    email: '[email protected]',
    id: 1,
    password: 'vasa',
    token: 1,
    username: 'jack' } ]

But I get

[  ,
      { clubID: 4,
        displayName: 'Jack',
        email: '[email protected]',
        id: 1,
        password: 'vasa',
        token: 1,
        username: 'jack' } ]

What's the trouble? When looking for a second user, then everything is fine.

Upvotes: 0

Views: 1045

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

You're storing your user info with numeric keys (1,2,3, etc). When you do this, the Firebase SDK may try to convert the result into an array. For an explanation of when it does this, see our blog post Best Practices: Arrays in Firebase.

The bottom line is: don't use numeric, sequential keys for items in Firebase. Instead:

  • If the items have a natural key, store them under that natural key
  • If the items don't have a natural key, use Firebase push IDs as the key

Since you're storing users, it's common practice to use the UID of each user as their key.

But since your User IDs don't look like Firebase Authentication UIDs, that might leave the same problem. In that case, you can keep using your current keys, but in that case prefix them with a string to prevent the array coercion of the SDK. So:

"Users": {
  "User1": {
    ...
  }
  "User2": {
    ...
  }
}

Upvotes: 1

Related Questions