【发布时间】:2022-02-09 23:49:27
【问题描述】:
我有一个 Firebase 函数,可以在删除评论时减少评论计数,就像这样
export const onArticleCommentDeleted = functions.firestore.document('articles/{articleId}/comments/{uid}').onDelete((snapshot, context) => {
return db.collection('articles').doc(context.params.articleId).update({
commentCount: admin.firestore.FieldValue.increment(-1)
})
})
我还有 firebase 函数,可以在删除文章时递归删除文章的 cmets
export const onArticleDeleted = functions.firestore.document('articles/{id}').onDelete((snapshot, context) => {
const commentsRef = db.collection('articles').doc(snapshot.id).collection('comments');
db.recursiveDelete(commentsRef); // this triggers the onArticleCommentDeleted multiple times
})
当我删除一篇文章时,会触发 onArticleCommentDeleted 并尝试更新已删除的文章。当然,我可以在更新之前检查文章是否存在。但是真的很麻烦,也很浪费资源。
有什么方法可以避免进一步传播触发器?
【问题讨论】:
-
另一种方法是将commentCount 存储在另一个名为article_aggregation 的具有相同ID 的集合中。因此,当一篇文章被删除时,onArticleCommentDeleted 会更新 article_aggregation 中的文档而不是文章集合。这样可以避免更新不存在的文章。但这会将垃圾文档留在 article_aggregation 中。当你加载一篇文章时,它需要额外阅读相应的 article_aggregation 以获得 commentCount。
标签: node.js google-cloud-firestore google-cloud-functions event-propagation