0

How do I retrieve the random ID key generated by Firebase?

For example, if I have this:

    users
    │
    ├──── KT4NTZTzFduj3DNLQgg
    │     │
    │     ├────  uid: "7ZLldIsRu3NQMOb6"
    │     └────  username: "John"
    │
    │
    └──── TO39dsjk2wREF34kmcs // I want this
          │
          ├────  uid: "455klfmckjsnenk2sxkm2"
          └────  username: "Micheal"

I want to get the key which holds a username with value equal to Micheal.

firebase.database()
    .ref('users')
    .orderByChild("username")
    .equalTo("Micheal")
    .once("value", 
            function (snapshot) {
                // what should I write here ??
            });
Nicolás Alarcón Rapela
  • 2,714
  • 1
  • 18
  • 29
splunk
  • 6,435
  • 17
  • 58
  • 105
  • I believe its `snapshot.key` – eshirima Oct 02 '16 at 18:13
  • Possible duplicate of [In Firebase when using push() How do I pull the unique ID](http://stackoverflow.com/questions/16637035/in-firebase-when-using-push-how-do-i-pull-the-unique-id) – dafyk Oct 02 '16 at 18:18

1 Answers1

0

The query will return a snapshot containing the matching children under users.

You can enumerate the children and obtain the matching child's key via the child snapshot's key property:

firebase.database().ref("users")
  .orderByChild("username")
  .equalTo("Micheal")
  .once("value", function (snapshot) {

    var key;

    snapshot.forEach(function (childSnapshot) {
      key = childSnapshot.key;
      return true; // Cancel further enumeration.
    });

    if (key) {
      console.log("Found user: " + key);
    } else {
      console.log("User not found.");
    }
  });
cartant
  • 57,105
  • 17
  • 163
  • 197