Javascript Firebase-按值搜索子级
假设我的Firebase上有以下数据:Javascript Firebase-按值搜索子级,javascript,json,firebase,Javascript,Json,Firebase,假设我的Firebase上有以下数据: https://mygame.firebaseio.com/player { "player": { "bloodgulf01": { "username": "bloodgulf01", "uid": "twitter:102032", "level": 2, "map": 3, "x": 51, "y": 12 }, "damjanovic": {
https://mygame.firebaseio.com/player
{
"player": {
"bloodgulf01": {
"username": "bloodgulf01",
"uid": "twitter:102032",
"level": 2,
"map": 3,
"x": 51,
"y": 12
},
"damjanovic": {
"username": "damjanovic",
"uid": "github:77371",
"level": 5,
"map": 2,
"x": 21,
"y": 44
}
}
}
如何通过uid
进行搜索并获得结果的快照
以下是我尝试过的:
new Firebase("https://mygame.firebaseio.com/player")
.startAt(authData.uid)
.endAt(authData.uid)
.once('value', function(snap) {
console.log('accounts matching UID of ' + authData.uid, snap.val())
});
它返回:
与github的UID匹配的帐户:123456789 null
,尽管在/player/
的数据中有UID
。记住,Firebase中的所有内容都是url。因此,您可以这样做以获取所需的数据:
'https://mygame.firebaseio.com/player/' + uid
记住,Firebase中的所有内容都是url。因此,您可以这样做以获取所需的数据:
'https://mygame.firebaseio.com/player/' + uid
按要筛选的子级排序,然后筛选:
new Firebase("https://mygame.firebaseio.com/player")
.orderByChild('uid')
.equalTo(authData.uid)
.once('child_added', function(snap) {
console.log('account matching UID of ' + authData.uid, snap.val())
});
由于您只需要一名玩家,因此您可能只需使用一次('child_added'
)即可。如果您需要使用相同的uid处理多个玩家,则:
.on('child_added', function(snap) {
console.log('account matching UID of ' + authData.uid, snap.val())
});
或
尽管如此,我还是支持Chrillewoodz的结构:我总是希望看到
uid
作为用户集合的键。在这种情况下,您可以使用上述方法搜索名称。按要筛选的孩子排序,然后筛选:
new Firebase("https://mygame.firebaseio.com/player")
.orderByChild('uid')
.equalTo(authData.uid)
.once('child_added', function(snap) {
console.log('account matching UID of ' + authData.uid, snap.val())
});
由于您只需要一名玩家,因此您可能只需使用一次('child_added'
)即可。如果您需要使用相同的uid处理多个玩家,则:
.on('child_added', function(snap) {
console.log('account matching UID of ' + authData.uid, snap.val())
});
或
尽管如此,我还是支持Chrillewoodz的结构:我总是希望看到
uid
作为用户集合的键。在这种情况下,你可以用上面的方法搜索名称。是的,但它们不是作为uid存储的,而是作为播放器存储的usernames@DanF为什么不将用户名存储在uid instad下相反?由于uid总是唯一的,这比将密钥存储为玩家名称要好。@chrillewoodz我想,但我不知道如何在数据库中搜索用户名。是的,但它们不是作为uid存储的,而是作为玩家存储的usernames@DanF你为什么不把用户名存储在对方的uid地址下呢ce uid总是唯一的这是一个比将密钥存储为玩家名称更好的选择。@我想是Chrillewoodz,但是我不知道如何在数据库中搜索用户名。