3
votes

I am trying to write a cloud function that will keep track of the amount of Documents in the Collection. There isn't a ton of documentation on this probably because of Firestore is so now.. so I was trying to think of the best way to do this.. this is the solution I come up with.. I can't figure out how to return the count

Document 1 -> Collection - > Documents

In Document 1 there would ideally store the Count of Documents in the Collection, but I can't seem to figure out how to relate this

1

1 Answers

6
votes

Let's just assume Document1 is a Blog post and the subcollection is comments.

  1. Trigger the function on comment doc create.
  2. Read the parent doc and increment its existing count
  3. Write the data to the parent doc.

Note: If your the count value changes faster than once-per-second, you may need a distributed counter 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)
     })

}); 

I put together a detailed firestore aggregation example if you need to run advanced aggregation calculations beyond a simple count.