【问题标题】:Firebase function when updating another child field in document - change.before.ref.parent is not a function更新文档中的另一个子字段时的 Firebase 函数 - change.before.ref.parent 不是函数
【发布时间】:2023-02-09 20:34:34
【问题描述】:

我是 Firestore 函数的新手,我开始将它们与实时数据库结合使用。我想要实现的目标 - 如果 ' 下的任何字段分数' 集合发生变化(在本例中为 't1' 或 't2'),则 'round' 字段应递增 1。文档如下所示:

这是我的功能:

exports.onScoreChange = functions.database
.ref('games/{gameId}/scores')
.onWrite((change, context) => {
    console.log('Score of either player has changed');
    var round = change.before.ref.parent('gameInfo/round').get('round') + 1; 
    console.log('Rounds so far: ' + round);
    return change.ref.parent('gameInfo/round').set(round);
});

当我查看日志时,该函数被触发,因为我可以在日志中看到消息“任一玩家的分数已更改”,但随后我收到此错误:

change.before.ref.parent is not a function

我的逻辑流程是,我应该在文档上方执行一个“步骤”,这样我就可以访问属于游戏“gameInfo”集合的其他字段 - 然后我可以访问字段“round”并更改它。脚本有什么问题?

【问题讨论】:

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


    【解决方案1】:

    您收到的错误是因为change.before.ref.parent 是一个属性,它不是一个方法,请参考this official documentation 如果您在创建 firebase 函数时使用了打字稿,则可以避免这种情况。我建议您使用child访问,而不是像那样访问

    const roundRef = change.before.ref.parent?.child("gameInfo/round"); //⇐ Using child
    

    scores 的父级是{gameId},所以与gameInfo/round 一样,{gameId} 的子级。

    所以更新的功能将是:

    exports.onScoreChange = functions.database.ref("games/{gameId}/scores")
        .onWrite((change, context) => {
          console.log("Score of either player has changed");
          const roundRef = change.before.ref.parent?.child("gameInfo/round");
          return roundRef?.transaction((round) => {
            return round + 1;
          });
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-20
      • 2019-12-04
      • 2021-09-04
      • 2021-10-13
      • 2019-09-18
      • 2017-11-10
      • 2019-05-19
      • 2022-11-25
      相关资源
      最近更新 更多