![](/img/trans.png)
[英]Firebase cloud function taking over 5 minutes to update database
[英]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.