【问题标题】:onDelete not being called when deleting a node in Cloud Functions for Firebase在 Cloud Functions for Firebase 中删除节点时未调用 onDelete
【发布时间】:2017-08-09 21:57:26
【问题描述】:

我正在尝试围绕追随者和追随者为 Firebase 应用构建触发器。下面是我的云代码的 sn-p。当用户关注时,我想增加一个计数器。为此,我使用 oncreate(当用户获得他们的第一个追随者时,由于结构在此之前不存在),然后我使用 onupdate。然后,当用户取消关注并被删除时,我使用 ondelete 减少以下计数。

我遇到的问题是 .ondelete 没有被调用,而只有 .onupdate 被调用,而不管用户是否被添加或删除(我想回顾一下是有道理的)。我的问题是如何编写云函数来区分删除和添加。

数据库看起来像这样

user1
  - following
     -user2
       -small amount of user2data
     -user3
       -small amount of user3data

还有代码:

    exports.countFollowersUpdate = functions.database.ref('/{pushId}/followers/')
        .onUpdate(event => {

          console.log("countFollowers")


          event.data.ref.parent.child('followers_count').transaction(function (current_value) {

            return (current_value || 0) + 1;
          });


        });

exports.countFollowersCreate = functions.database.ref('/{pushId}/followers/')
    .onCreate(event => {

      console.log("countFollowers")


      event.data.ref.parent.child('followers_count').transaction(function (current_value) {

        return (current_value || 0) + 1;
      });


    });


exports.countFollowersDelete = functions.database.ref('/{pushId}/followers/')
    .onDelete(event => {

      console.log("countFollowers2")


      event.data.ref.parent.child('followers_count').transaction(function (current_value) {

        if ((current_value - 1) > 0) {
          return (current_value - 1);
        }
        else{
          return 0;
        }
      });

【问题讨论】:

  • 再次阅读我的问题。服务器不知道它是关注还是取消关注。它只知道数据是如何被编辑的。问题是它无法区分更新和删除。至于您的第一个问题,从效率的角度来看,每笔交易都计算整个数字是很可怕的。
  • 请说明客户端我如何将数据添加到数据库中。另请注意,您的数据库结构在您的问题中是不可读的 - 它需要格式化。

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


【解决方案1】:

onDelete 没有被调用,因为您正在收听整个 followers 节点,所以它只会在跟随者计数变为零时被调用(什么都不剩)。相反,您可能希望所有这些都更像:

functions.database.ref('/{pushId}/followers/{followerId}').onDelete()

您拥有顶级推送 ID 也是不寻常的。结构通常更像/users/{pushId}/followers/{followerId}

【讨论】:

    猜你喜欢
    • 2017-09-25
    • 2019-10-12
    • 2017-09-11
    • 2017-09-09
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2017-08-07
    相关资源
    最近更新 更多