0

我正在尝试为下面的追随者和关注者构建一个Firebase应用的触发器。以下是我的云代码片段。我想在用户关注时增加计数器。为此,我使用oncreate(因为当用户获得他们的第一个追随者时,由于该结构不存在,直到此时),然后使用onupdate。然后,我使用ondelete在用户取消关注和删除时减少以下计数。onDelete在云端函数中删除一个节点时未被调用Firebase

我遇到的问题是.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; 
     } 
     }); 
+0

再次阅读我的问题。服务器不知道它是关注还是取消关注。它只知道数据是如何编辑的。问题是它无法区分更新和删除之间的区别。至于你的第一个问题,从效率的角度来看,每次交易都要统计整个数字是非常可怕的。 – Blue

+0

请指出客户端如何将数据添加到数据库。另外请注意,你的问题中你的数据库结构是不可读的 - 它需要格式化。 –

回答

1

onDelete不会被调用,因为你正在收听的是整个followers节点,所以它只会是当追随者数量变为零时(没有任何遗漏)调用。相反,你可能想所有这些更像:

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

这也是不寻常的,你有一个顶级推ID。结构通常更像/users/{pushId}/followers/{followerId}

相关问题