Firebase Cloud function update all entries in database

前端 未结 1 1580
清酒与你
清酒与你 2021-01-25 22:38

i have bunch of comments in Firebase database and i want to do some updates to the comments via Cloud Function ( this is simplified example, i will be doing some logic which doe

相关标签:
1条回答
  • 2021-01-25 22:50

    If you want to update all child nodes, you can do something like this:

    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);
    })
    

    This performs a single multi-location update for all comments. Note that the performance benefit over performing separate updates is quite small, since Firebase pipelines the multiple requests over a single connection.

    Also note that you should not put this in a Cloud Functions trigger on /comments, since that will lead to an endless loop: every time the comments get written, your function triggers, which updates the comments, which triggers the function again.

    If you need this in Cloud Functions, you'll want to use a HTTP-triggered function, which is triggered by HTTP calls instead of database writes.

    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");
        });
      })
    })
    

    You can then periodically call this URL/function with a service like cron-job.org. For more on this see Cloud Functions for Firebase trigger on time?.

    0 讨论(0)
提交回复
热议问题