【问题标题】:Firebase Cloud Functions - Realtime Database - Get parent node keyFirebase Cloud Functions - 实时数据库 - 获取父节点密钥
【发布时间】:2020-09-25 13:58:34
【问题描述】:

我正在尝试从快照中获取父节点的密钥。为了确认,当我打印snapshot.val() 时,我从下面的函数中获取了正确的节点数据,所以问题不在于查询,但我似乎找不到获取返回快照密钥的方法。

/games
   |--{game_id} ==> get this id
         |---"alias":"123456" ==> from the snapshot returned by querying this
         |---"players":...
         |..... // other childs of game_id

这里是云函数代码:

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


});


【问题讨论】:

    标签: typescript firebase-realtime-database google-cloud-functions


    【解决方案1】:

    将代码更改为可以工作:

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

    【讨论】:

    • 是的,它按预期返回了 game_id,但请注意别名是唯一的代码,所以我只有一个结果。如果您有多个与查询匹配的节点,则必须更改 foreach 中的逻辑
    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 2019-09-25
    • 2019-10-03
    • 2017-10-02
    • 1970-01-01
    • 2019-04-13
    • 2020-05-12
    • 1970-01-01
    相关资源
    最近更新 更多