如何从 Firebase 数据快照中获取密钥?

39

我能够通过电子邮件地址查询我的users数组并返回用户的帐户信息:

users.orderByChild('email').equalTo(authData.user.email).once('value').then(function(snapshot) {
        console.log(snapshot.val());
        console.log(snapshot.key); // 'users'
        console.log(snapshot.child('email').key); 'email'
        ...

这里输入图片描述

如何获取键(-KiBBDaj4fBDRmSS3j0r)。snapshot.key返回userssnapshot.child('email').key返回email。该键似乎不是子级,即它似乎在usersemail之间。

5个回答

50

1
快速响应!谢谢! - Thomas David Kehoe

32

实时数据库:

您可以简单地使用:snapshot.key

快照 = firebase.database.DataSnapshot

this.app.database()
        .ref('/data/')
        .on('value', function(snapshot) {
            const id = snapshot.key;

            //----------OR----------//
            const data = snapshot.val() || null;
            if (data) {
              const id = Object.keys(data)[0];
            }
        });

Firestore:

snapshot.id

snapshot = firebase.firestore.DocumentSnapshot

this.app.firestore()
        .collection('collection')
        .doc('document')
        .onSnapshot(function(snapshot) {
            const id = snapshot.id;

            //----------OR----------//
            const data = snapshot.data() || null;
            if (data) {
              const id = Object.keys(data)[0];
            }
        });

相比其他答案,这是最正确的答案。 - Abhishek Batra

6

users.orderByChild('email').equalTo(authData.user.email)是一个查询(文档),您可以通过“链接一个或多个筛选方法”来构建它。您查询的内容比较特殊,因为它使用equalTo(authData.user.email)进行查询,它只返回一个子数据快照

此处所述,在这种情况下,您应该使用forEach()循环遍历返回的数据快照:

Attaching a value observer to a list of data will return the entire list of data as a single snapshot which you can then loop over to access individual children.

Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result, as follows:

ref.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...
  });
});

1
这实际上是 Firebase 文档推荐的方式! - Yo Apps

5

和 camden_kid 一样,我使用 Object.keys(arr),但是需要三行代码:

var arr = snapshot.val();
var arr2 = Object.keys(arr);
var key = arr2[0];
console.log(key) // -KiBBDaj4fBDRmSS3j0r

3
我找到了一种基于快照键获取数据的新方法 -
 firebase.database().ref('events').once('value',(data)=>{
      //console.log(data.toJSON());
      data.forEach(function(snapshot){
        var newPost = snapshot.val();
        console.log("description: " + newPost.description);
        console.log("interest: " + newPost.interest);
        console.log("players: " + newPost.players);
        console.log("uid: " + newPost.uid);
        console.log("when: " + newPost.when);
        console.log("where: " + newPost.where);
      })
      })

我遇到了与 OP 几乎相同的问题,最终我使用了 foreach/for 等方法获取了信息,但由于作用域的原因,我失去了这些值。您有什么建议吗?这将非常有帮助。 - Marco Santana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接