我正在尝试围绕关注者和关注者为 firebase 应用程序构建触发器。下面是我的云代码片段。我想在用户关注时增加一个计数器。为此,我使用 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;
}
});
最佳答案
onDelete
没有被调用,因为你正在监听整个 followers
节点,所以它只会在关注者计数变为零(什么都没有)时被调用.相反,您可能希望所有这些更像是:
functions.database.ref('/{pushId}/followers/{followerId}').onDelete()
您拥有顶级推送 ID 也很不寻常。结构通常更像 /users/{pushId}/followers/{followerId}
。
关于javascript - 在 Cloud Functions for Firebase 中删除节点时未调用 onDelete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45601260/