未调用onDelete数据库触发器

时间:2018-03-01 06:49:20

标签: firebase google-cloud-functions

我有两个相互否定的云函数,如下所示:

    exports.onPostLiked = functions.database.ref('userpostlikescomments/{uid}/{pushId}/likes/list/{uid2}')
.onCreate(event => {
    //runs w/o error
    const numsRef = event.data.ref.parent.parent.child('num');
    numsRef.transaction(currentData => {
        return (currentData || 0) + 1;
    });
});

exports.onPostUnliked = functions.database.ref('userpostlikescomments/{uid}/{pushId}/likes/list/{uid2}')
.onDelete(event => {
    const numsRef = event.data.ref.parent.parent.child('num');
    numsRef.transaction(currentData => {
        return (currentData || 0) - 1;
    });
});

onPostLiked被调用并且有效,但是当我删除刚刚在指定路径创建的内容时,根本不会调用onPostUnliked函数。为什么会这样呢?

我做了以下添加和删除节点:

enter image description here 我去了所需的节点 enter image description here 我在列表中添加了另一个元素,更新了元素数量 enter image description here 我们可以看到调用onPostLiked云函数,记下时间 enter image description here 然后我们删除创建的节点 enter image description here onPostUnLiked没有被调用,再次注意时间 enter image description here 元素的数量没有得到更新

2 个答案:

答案 0 :(得分:1)

更改onDelete()中的路径:

ref('userpostlikescomments/{uid}/{pushId}/likes/list/{uid2}')

到此:

ref('userpostlikescomments/{uid}/{pushId}/likes/list/two')

并在删除项目时触发。

此外,最好使用console.log来记录正在添加的内容或您在哪条路径上。

答案 1 :(得分:0)

您可以尝试对给定路径使用一个触发器onChange,并检查事件的实际类型,例如:

exports.onPostLikeOrUnlike = functions.database.ref('userpostlikescomments/{uid}/{pushId}/likes/list/{uid2}')
.onChange(event => {
    if(event.data.previous.val() === null) {
        //There was no previous value in the db, thus execute onCreate functionality
    }

    if(event.data.val() === null) {
         //In this case, we know that there has been a previous value, but there is no current value, thus this execute onDelete functionality.        
    }

    //If the conditions above weren't true, that means we've previous and current values as well, so this is an onUpdate event.
});