云功能-更新Firebase数据库中的数据

时间:2018-07-27 14:09:15

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

我正在使用Cloud函数计算帖子中有多少评论。 当我添加评论时,它将其保存在Firebase数据库中,然后在Cloud函数上,有一个函数会侦听“ Comments”节点,并应“ +1”回到Firebase数据库。

由于某种原因,它仅在我从Firebase数据库中删除评论时才有效。 当我删除评论时,添加“ +1”。

那是我的代码

    exports.commentsCount = functions.database.ref('/comments/{commentid}/{userUID}').onWrite(event =>{
const collectionRef = event.data.ref.parent;
const model = event.data.previous.val();
const commentid = event.params.commentid;

console.log("commentID:",commentid);

const countComments = collectionRef.child('countComments');


return countComments.transaction(current => {
  console.log('Before the If');
  if (!event.data.exists() && event.data.previous.exists()) {
    console.log('Enter to the if.');
    const commentsList = admin.database().ref(`comments/${commentid}/countComments`).transaction(current => {
      return (current || 0) + 1;
    });
  }
}).then(() => {
      console.log('Comments counter updated.');
         });  
    });

任何人都可以告诉我我在哪里做错了吗?

1 个答案:

答案 0 :(得分:0)

您正在使用它来确定何时触发函数:

exports.commentsCount = functions.database.ref('/comments/{commentid}/{userUID}').onWrite(event =>{

此处的关键是您使用onWrite,这意味着该函数将针对/comments/{commentid}/{userUID}下的任何写操作触发。

由于只添加计数,因此仅当添加新注释时,函数才能运行。为此,您应该使用onCreate而不是onWrite

exports.commentsCount = functions.database.ref('/comments/{commentid}/{userUID}').onCreate((snapshot, context) =>{
  const collectionRef = snapshot.ref.parent;
  const model = snapshot.val();
  const commentid = context.params.commentid;

我还更新了参数,使其与1.0 Firebase Functions库匹配。有关更多信息,请参见upgrade guide