3

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

joe
  • 151
  • 3
  • 8
  • 1
    Possible duplicate of [How to get a count of number of documents in a collection with Cloud Firestore](https://stackoverflow.com/questions/46553314/how-to-get-a-count-of-number-of-documents-in-a-collection-with-cloud-firestore) – Doug Stevenson Dec 06 '17 at 21:30

1 Answers1

7

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.

JeffD23
  • 8,318
  • 2
  • 32
  • 41
  • Did anything change with that behaviour? I try to rebuild your example but the `event.params` doesnt exist. `Property 'params' does not exist on type 'DocumentSnapshot'.` – niclas_4 Jan 10 '19 at 09:30
  • Got it sorted out with `((change,context) => ...` – niclas_4 Jan 10 '19 at 09:35