Firebase功能datasnapshot不起作用

时间:2018-09-02 12:23:23

标签: node.js firebase firebase-realtime-database google-cloud-firestore

我正在尝试在firebase函数中运行下一个代码,但它给出了无法识别datasnapshot的错误。是什么原因引起的?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


exports.updateVotes = functions.database.ref('travels/{travelId}/locations/{locationId}/voting/users')
.onUpdate((userVotes, context) => {
    var travelId = context.params.travelId;
    var locationId = context.params.locationId
    var sumVotes = 0;

    userVotes.forEach((userVote) => {
        sumVotes += userVote.val().userVote;

    })
    // var votes = userVotes.val();
    // for (var vote in votes) {
    //     if (votes.hasOwnProperty(vote)) {
    //         sumVotes += votes[vote].userVote;
    //     }
    // }

    return admin.database()
        .ref('travels/' + travelId + '/locations/' + locationId + '/voting')
        .update({ votes: sumVotes })

})

错误是:

  

TypeError:userVotes.forEach不是exports.updateVotes.functions.database.ref.onUpdate上的函数

1 个答案:

答案 0 :(得分:2)

onUpdate不返回DataSnapshot,而是返回Change对象。

您需要选择afterbefore属性-在写入之前还是写入之后(通常是之后的-这是Firebase中的新数据)需要信息吗?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


exports.updateVotes = functions.database.ref('travels/{travelId}/locations/{locationId}/voting/users')
.onUpdate((change, context) => {
    var travelId = context.params.travelId;
    var locationId = context.params.locationId
    var sumVotes = 0;

    var userVotes = change.after;

    userVotes.forEach((userVote) => {
        sumVotes += userVote.val().userVote;

    })

    return admin.database()
        .ref('travels/' + travelId + '/locations/' + locationId + '/voting')
        .update({ votes: sumVotes })

})