【问题标题】:Cloud functions - update data in firebase database云功能 - 更新 firebase 数据库中的数据
【发布时间】:2018-07-27 14:09:14
【问题描述】:

我正在使用云函数来计算帖子中有多少 cmets。 当我添加评论时,它会将其保存在 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.');
         });  
    });

谁能告诉我我哪里做错了?

【问题讨论】:

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


    【解决方案1】:

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

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

    这里的关键是你使用onWrite,这意味着这个函数会被/comments/{commentid}/{userUID}下的any写操作触发。

    由于您只是添加到计数中,因此您的函数应该仅在添加新评论时运行。为此,您应该使用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 函数库。有关更多信息,请参阅upgrade guide

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2018-08-20
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多