Firebase Cloud Functions设置值操作会删除触发器发起节点

时间:2018-05-25 04:36:02

标签: firebase firebase-realtime-database google-cloud-functions

enter image description here

您好,上面是我在firebase的实时数据库中的简单数据结构。我正在研究一个简单的云功能,它将在用户节点中收听更新并得分。财产和更新平均分数'位于层次结构中较高的字段。

这是我的onWrite回调:

import itertools as it
import operator as op

def print_table(tc, n):
    name, value = op.itemgetter(0), op.itemgetter(1)
    for k, g in it.islice(it.groupby(tc.most_common(), value), n):
        print(k, ' '.join(sorted(map(name, g))))

In []:
print_table(tweet_counter, 2)

Out[]:
4 sam
2 andrew fred

In []:
print_table(tweet_counter, 3)

Out[]:
4 sam
2 andrew fred
1 dean judy

如果我更新userId 1234的得分,则 averageScore 字段会根据此代码正确更新。但是,整个用户Id节点1234在此更新后获得 DELETED 。这是一个令人头疼的问题,并希望从社区中获得一些关于我可能做错的事情的见解。

干杯。

1 个答案:

答案 0 :(得分:1)

.onWrite((change, context) => {

    if ( !change.before.exists() || !change.after.exists()) {
        return null;
    }

    const beforeScore = parseFloat(change.before.val()['score']);
    const afterScore = parseFloat(change.after.val()['score']);
    const crowdStatsRef = change.after.ref.parent.parent.child('crowdStats');

    return Promise.all( [
        crowdStatsRef.child('userCount').once('value'),
        crowdStatsRef.child('averageScore').once('value')
    ]).then((snapshots) => {
        return crowdStatsRef.transaction((crowdStatsNode) => {

            if (crowdStatsNode) {
                const userCount = snapshots[0].val();
                const averageScore = snapshots[1].val();

                const currentAverage = (( ( averageScore * userCount ) - beforeScore + afterScore ) / userCount ).toFixed(2);
                crowdStatsNode.score = parseFloat(currentAverage);
            }

            return crowdStatsNode;
        }, (error, committed, snapshot) => {
            if (error) {
                console.error(error);
            }
        });
    });
});

误解了交易的运作方式。必须在回调函数中返回要锁定的对象。此外,在此回调函数中的空检查是必不可少的。

这里举例说明: https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html