簡體   English   中英

Firebase Cloud功能更新數據庫中的所有條目

[英]Firebase Cloud function update all entries in database

我在Firebase數據庫中有很多注釋,我想通過Cloud Function對注釋進行一些更新(這是簡化的示例,我將做一些確實需要Cloud Function的邏輯)。

我需要做的是遍歷數據庫中的所有注釋,調整其評級節點,然后使用調整后的注釋更新數據庫。

我花了很多時間研究這個問題,但是我對Cloud Functions完全陌生,因此我很難解決這個問題。 我假設我想將對所有注釋的所有更改(可能有成千上萬個)存儲在數組或對象中,然后一次進行更新,而不是分別為每個注釋進行更新?

順便說一句,此代碼不起作用,我假設數組和返回是完全錯誤的。

exports.increaseRating = functions.database.ref('/comments/')
    .onUpdate((snapshot) => {   

        var updates = [];

        snapshot.before.forEach((element) => {
            var comment = element.val();
            comment.rating += 1000;
            updates.push(comment);
        });

        return updates;
    })

我用來更新一個條目的代碼。 我需要一次對所有評論執行相同的操作。

exports.increaseRating = functions.database.ref('/comments/{commentId}')
    .onUpdate((snapshot, context) => {

        const comment = snapshot.before.val();
        const newRating = comment.rating += 1000;       

        const now = new Date().getTime();
        if (comment.lastUpdate) {
            if (comment.lastUpdate > now - (30 * 1000)) {
                return null;
            }
        }

        return admin.database().ref(`/comments/${context.params.commentId}`).update({
            "rating": newRating,
            "lastUpdate": now
        })
    })

如果要更新所有子節點,可以執行以下操作:

var ref = firebase.database().ref("comments"); // or admin.database().ref("comments")
ref.once("value").then((snapshot) => {
  var updates = {};
  snapshot.forEach((commentSnapshot => {
    var comment = commentSnapshot.val();
    var newRating = comment.rating + 1000;
    updates[commentSnapshot.key+"/rating"] = newRating;
  });
  ref.update(updates);
})

這將對所有注釋執行單個多位置更新。 請注意,與執行單獨的更新相比,性能優勢非常小,因為Firebase通過單個連接流水線處理多個請求

還要注意的是,你應該把這個在雲功能觸發/comments ,因為這將導致一個死循環:每一個意見被寫入的時候,你的功能觸發,這將更新的評論,這再次觸發功能。

如果在Cloud Functions中需要此功能,則需要使用HTTP觸發的功能,該功能由HTTP調用而不是數據庫寫入觸發。

exports.updateCommentRatings = functions.https.onRequest((req, res) => {
  var ref = admin.database().ref("comments")
  ref.once("value").then((snapshot) => {
    var updates = {};
    snapshot.forEach((commentSnapshot => {
      var comment = commentSnapshot.val();
      var newRating = comment.rating + 1000;
      updates[commentSnapshot.key+"/rating"] = newRating;
    });
    ref.update(updates).then(() => {
      res.status(200).send("Comment ratings updated");
    });
  })
})

然后,您可以使用cron-job.org之類的服務定期調用此URL /函數。 有關更多信息,請參閱針對Firebase的雲功能是否按時觸發?

暫無
暫無

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

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