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;
}
});
再次閱讀我的問題。服務器不知道它是關注還是取消關注。它只知道數據是如何編輯的。問題是它無法區分更新和刪除之間的區別。至於你的第一個問題,從效率的角度來看,每次交易都要統計整個數字是非常可怕的。 – Blue
請指出客戶端如何將數據添加到數據庫。另外請注意,你的問題中你的數據庫結構是不可讀的 - 它需要格式化。 –