簡體   English   中英

雲功能-更新Firebase數據庫中的數據

[英]Cloud functions - update data in firebase database

我正在使用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.');
         });  
    });

有人可以告訴我即時消息做錯了什么嗎?

您正在使用它來確定何時觸發函數:

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庫匹配。 有關更多信息,請參見升級指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM