使用Firebase的云功能进行增量操作

时间:2017-05-10 12:38:18

标签: javascript node.js firebase google-cloud-functions

我正在尝试使用Cloud Functions for Firebase为我的数据库创建一个函数。该函数的目的是监听attend表上的写事件,并基于所写的对象来识别事件并增加事件对象上的usersAttending

到目前为止,这是我的功能。

//listens to write on attendObjects (when a user is attending an event), and increments attending users for event 
exports.listenAttendingEvents = functions.database.ref('/attend/{pushId}').onWrite(event => {

//get attendObj -> parsed JSON by javascript interpreter
const attentObj = event.data.val();
const attendId = attentObj['attendId'];
const pathToAttendees = '/attends' + '/' + attendId;

// Attach an asynchronous callback to read the data at our posts reference
 admin.database().ref(pathToAttendees).on("value", function(snapshot) {
  console.log(snapshot.val());
  const obj = snapshot.val();
    var nrAttending = obj['attending'];
         nrAttending = Number(snapshot.val());
         return admin.database().ref(pathToAttendees + '/attending').transaction(function (nrAttending) {
             return (nrAttending || 0) + 1;
        }); 
    });
}, function (errorObject) {
   console.log("The read failed: " + errorObject.code);
   return errorObject
});

似乎问题是event object没有被检索到。该功能似乎在状态ok

之前完成

1 个答案:

答案 0 :(得分:0)

问题在于我没有承诺我的顶级功能。这导致Google Cloud Functions在操作完成之前将其终止。

添加承诺解决了我的问题

admin.database().ref(pathToAttendees).once("value").then( function(snapshot) {