我正在尝试从快照中获取父节点的密钥。确认一下,我在打印snapshot.val()
时从下面的函数中获取了正确的节点数据,所以问题不在于查询,但是我似乎找不到找到返回键的方法。快照。
/games
|--{game_id} ==> get this id
|---"alias":"123456" ==> from the snapshot returned by querying this
|---"players":...
|..... // other childs of game_id
这是cloudfunction代码:
export const getGameIDFromCode = functions.https.onCall((data, context) => {
if (context.auth == null) {
throw new functions.https.HttpsError('permission-denied', 'You are not authorized to use this feature');
}
const code = data.code;
const gamesRef = db.ref("/games");
return gamesRef.orderByChild("alias").equalTo(code).once("value").then(snapshot => {
if (snapshot.ref.parent != null) {
// tried snapshot.key => returns "games"
// tried snapshot.ref.key ==> returns "games"
return snapshot.ref.parent.key;
} else {
return "Unable to find game_id for the code";
}
}).catch(error => {
return error;
});
});
答案 0 :(得分:0)
将代码更改为此可以使用:
return gamesRef.orderByChild("alias").equalTo(code).limitToLast(1).once("value").then(snapshot => {
let gameId;
snapshot.forEach(child => {
gameId = child.key;
})
return gameId;
}).catch(error => {
return error;
});