firebase云功能事务偶尔工作

firebase云功能事务偶尔工作,firebase,triggers,transactions,firebase-realtime-database,google-cloud-functions,Firebase,Triggers,Transactions,Firebase Realtime Database,Google Cloud Functions,我有这样的云函数: exports.updateNewsCount = functions.database.ref('/channels/{channelId}/news/{newsId}/') .onWrite (event => { const channelId = event.params.channelId; const newsId = event.params.newsId; let CntRef = admin.database().ref('/

我有这样的云函数:

exports.updateNewsCount = functions.database.ref('/channels/{channelId}/news/{newsId}/') 
.onWrite (event => {
    const channelId = event.params.channelId;
    const newsId = event.params.newsId;
    let CntRef = admin.database().ref('/channelDetails/' + channelId + '/newsCnt');
    if (event.data.exists() && !event.data.previous.exists()){
        return CntRef.transaction(function(current){
            if (current){
                console.log ('current is not null');
                return (current || 0) + 1;
            }
            else {
                console.log('current is null');
                return current;
            }
        },function(error, b, d){
            if (error) 
                console.log(error);
            else 
                console.log ('error is null');
            if (b)
                console.log('boolean is true');
            else
                console.log('boolean is false');

            if (d)
                console.log('snapshot is ' + d);
            else
                console.log ('snapshot is null');
        }).then(()=>{});
    } else if (!event.data.exists() && event.data.previous.exists()){
        return CntRef.transaction(function(current){
            if (current)
                return (current || 1) - 1;
            else
                return current;
        }, function(error, b, d){if (error) console.log(error); if (d) console.log(d);}).then(()=>{});
    }
});

它持续地激发,因为我可以看到日志条目。但是,newsCnt字段未按预期更新。有时更新,有时不更新!!!我在这里做错了什么?

您应该期望一个事务可能会被调用多次,第一次使用null。这就是事务处理的工作方式。请阅读文档

特别注意该部分中的以下标注:

注意:因为update函数被多次调用,所以它必须 能够处理空数据。即使您的数据库中存在现有数据 远程数据库,当事务发生时,它可能不会在本地缓存 函数运行,导致初始值为null


您是否尝试过在期望事务执行的各个点进行登录,以查看它实际在做什么?是的。在多个位置添加了console.log,当它工作时,日志与预期的一样。云函数也总是返回ok状态。所以我知道没有语法错误。每次需要云函数时都会正确地启动它。根据日志,函数返回状态为ok。当它工作时,(我在上面的代码中剥离的my console.logs)告诉我该事务被尝试了两次,一次是在current为null时,第二次是在current不为null时。我有一种感觉,可能还有其他云功能阻止了这一过程的完成或类似的事情。在我转到firebase控制台并手动修改newsCnt字段(比如将其设置为1)一次后,它开始稳定地工作。在我这么做之前,firebase似乎不认为newsCnt字段是int字段。是的,我已经理解了。我想我在代码中也考虑到了这一点。当current为null时,我返回current。如果为事务的onComplete参数提供函数并记录其参数,您会发现什么?交易绝对不会破裂。我已经修改了代码,包括onComplete和console.log。我的日志显示current为null(两次),boolean为true(一次),snapshot为[object object](一次),函数执行耗时1297毫秒,状态为“ok”(一次)@Dough如果您试图通过事务更改的位置没有数据,我会这么想。如果您正在尝试更新计数器,我想这段示例代码可能会对您有所帮助。请注意,存在性检查在事务内部,而您的检查在事务外部):现在另一个函数不起作用。我有另一个云功能来更新订阅者的数量。这很好用。现在没有了。日志显示当前值始终为null,函数返回ok。云功能内部的事务似乎已中断。谁来帮忙。