javascript - Firebase Cloud 函数更新数据库中的所有条目

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

我在 Firebase 数据库中有一堆评论,我想通过 Cloud Function 对评论进行一些更新(这是简化的示例,我将执行一些需要 Cloud Function 的逻辑)。

我需要做的是遍历数据库中的所有评论,调整其评分节点,然后使用调整后的评论更新数据库。

我花了很多时间研究这个,但我对云函数完全陌生,所以我真的很难弄清楚这一点。 我假设我想将对所有评论(可能有数千个)的所有更改存储在数组或对象中,然后一次进行更新,而不是分别针对每个评论?

顺便说一句,这段代码不起作用,我假设数组和返回完全错误。

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 pipelines the multiple requests over a single connection .

另请注意,您不应该将其放入 /comments 上的 Cloud Functions 触发器中,因为这将导致无限循环:每次写入评论时,您的函数会触发,这会更新注释,从而再次触发该函数。

如果您在 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/函数。有关更多信息,请参阅 Cloud Functions for Firebase trigger on time? .

关于javascript - Firebase Cloud 函数更新数据库中的所有条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52429370/

相关文章:

javascript - 错误或成功提交表单时的警报消息

javascript - 时间选择在 jquery 中不起作用

javascript - 仅在页面验证后刷新页面

javascript - 警告 : functions are not valid as a react child question. ..是因为我的容器吗?

android - FCM 允许消息数据存储吗?

firebase - Firestore 聊天应用 - 构建消息主页

node.js - Firebase Cloud Functions + Express示例上的"Cannot GET"错误

node.js - 如何通过快速发布请求强制客户端重定向到登录页面?

node.js - 尝试连接到本地 Express 服务器时出现 "Cannot GET/"

ajax - go - 如何获取请求消息正文内容?