检索Firebase生成的随机ID密钥?

时间:2016-10-02 18:00:09

标签: javascript firebase firebase-realtime-database

如何检索Firebase生成的随机ID密钥?

例如,如果我有这个:

users
|
|---- KT4NTZTzFduj3DNLQgg
|     |
|     |----  uid: "7ZLldIsRu3NQMOb6"
|     |----  username: "John"
|
|
|---- TO39dsjk2wREF34kmcs // I want this
|     |
|     |----  uid: "455klfmckjsnenk2sxkm2"
|     |----  username: "Micheal"

我想获取一个包含值等于Micheal的用户名的密钥。

firebase.database().ref('users').orderByChild("username").equalTo("Micheal").once("value", function(snapshot) 
        {
            what should I write here??

        });

1 个答案:

答案 0 :(得分:0)

查询将返回包含users下的匹配子项的快照。

您可以通过子快照的key属性枚举子项并获取匹配的子项:

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.");
    }
  });