如何在Firebase中检索多个密钥? [英] How to retrieve multiple keys in Firebase?

查看:66
本文介绍了如何在Firebase中检索多个密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此数据结构:

{
    "users":{
        "user-1":{
            "groups":{
                "group-key-1":true,
                "group-key-3":true
            }
        }
    },
    "groups":{
        "group-key-1":{
            "name":"My group 1"
        },
        "group-key-2":{
            "name":"My group 2"
        },
        "group-key-3":{
            "name":"My group 3"
        },
        "group-key-4":{
            "name":"My group 4"
        },
    }
}

我可以通过以下方式获取特定用户的组:

I could get the groups of a particular user with:

firebase.database().ref('users/user-1/groups').on(...)

哪个会给我这个对象?

{
    "group-key-1":true,
    "group-key-3":true
}

所以现在我要检索这些组的信息.

So now I want to retrieve the info for those groups.

我最初的直觉是循环这些键并执行以下操作:

My initial instinct would be to loop those keys and do this:

var data = snapshot.val()
var keys = Object.keys(data)

for (var i = 0; i < keys.length; i++) {
    firebase.database().ref('groups/' + keys[i]).on(...)
}

这是在Firebase中的同一终结点上调用多个键的适当方法吗?

Is this the appropriate way to call multiple keys on the same endpoint in Firebase?

Firebase是否提供解决此问题的更好方法?

Does Firebase provide a better way to solve this problem?

推荐答案

这是在同一端点上调用多个键的适当方法 在Firebase中?

Is this the appropriate way to call multiple keys on the same endpoint in Firebase?

是的,通常,这是一种以这种方式检索每个组的好方法.

Yes, generally this is a good solution to retrieve every group this way.

Firebase是否提供解决此问题的更好方法?

Does Firebase provide a better way to solve this problem?

在这种情况下,我认为Firebase不提供任何其他功能/查询可能会有所帮助.

I don't think Firebase provides any other function/query that could help in this case.

无论如何,可以将ref保存在变量中并直接在对象的键上循环,这可以得到改进.另外,如果您只需要检索一次这些数据,则应使用once()而不是on()

Anyway, this could be improved saving the ref in a variable and looping on the keys of the object directly. Also, if you just need to retrieve those data once, you should use once() instead of on()

var groupRef =  firebase.database().ref('groups/')
var data = snapshot.val()

for (var groupID in data) {
    groupRef.child(data[groupID]).once(...)
}

另一种方法是使用Firebase的函数获取数据快照,例如forEach

Another way could be using Firebase's functions for the data snapshots, like forEach

snapshot.forEach(function(childSnapshot) {
      groupRef.child(childSnapshot.key).once(...)
})

这篇关于如何在Firebase中检索多个密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆