Firestore云功能 - 保留收集中文档量的数量



我正在尝试编写一个云功能,该功能将跟踪集合中的文档量。没有大量的文档,可能是因为现在是Firestore是如此。.所以我试图考虑最好的方法。如何返回计数

文档1->收集 ->文档

在文档1中,理想情况下将存储文档计数中的收藏集,但我似乎无法弄清楚如何将此

联系起来

让我们假设document1是a 博客文章,子集合为注释

  1. 在注释文档创建上触发函数。
  2. 阅读父档并增加其现有计数
  3. 将数据写给父档。

注意:如果您的计数值的变化速度比一次性更快,则您可能需要分布式计数器https://firebase.google.com/docs/firestore/solites/solutions/counters

exports.aggregateComments = functions.firestore
    .document('posts/{postId}/comments/{commentId}')
    .onCreate(event => {
    const commentId = event.params.commentId; 
    const postId = event.params.postId;
    // ref to the parent document
    const docRef = admin.firestore().collection('posts').doc(postId)

    return docRef.get().then(snap => {
           // get the total comment count and add one
           const commentCount = snap.data().commentCount + 1;
           const data = { commentCount }
           // run update
           return docRef.update(data)
     })
}); 

如果您需要在简单的计数之外运行高级聚合计算,则将详细的Firestore聚合示例汇总在一起。

最新更新