Firestore Cloud功能-收集集合中的文档数量

joe*_*joe 3 firebase google-cloud-firestore

我正在尝试编写一个云函数,以跟踪集合中文档的数量。关于这一点,可能没有很多文档,因为Firestore现在是如此。.所以我试图思考实现此目的的最佳方法。.这是我想出的解决方案。.我不知道如何返回计数

文件1->收集->文件

在文档1中,理想情况下将文档计数存储在集合中,但是我似乎无法弄清楚如何将其关联

Jef*_*D23 6

让我们假设Document1是Blog帖子,而子集合是comments

  1. 在创建注释文档时触发功能。
  2. 阅读父文档并增加其现有数量
  3. 将数据写入父文档。

注意:如果您的计数值更改速度超过每秒一次,则可能需要分布式计数器https://firebase.google.com/docs/firestore/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)
     })

}); 
Run Code Online (Sandbox Code Playgroud)

如果您需要运行除简单计数之外的高级聚合计算,我将整理一个详细的Firestore聚合示例