简体   繁体   中英

Firestore Cloud Functions - Keeping Count of Amount of Documents in Collection

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM