简体   繁体   中英

How do a query a number from documents and sum it all up into a parent document in firestore using firebase functions

I have a collection of documents and i have a function that counts each document and saves the count into the parent document and is updated everytime a new document is created. I wanted to query that field and add it to its parent document to sum it all up. I need help coming up with a code that queries the all the fields from different documents and sum it all in the parent document

Here is my code that counts each document and saves it as a document field

const yearId = context.params.yearId; 
const daysId = context.params.daysId;
const monthId = context.params.monthId;
const ticketsId = context.params.ticketsId;

// ref to the parent document
//const docRef = admin.firestore().collection('TrafficViolations').doc(TrafficViolationsId)
const docRef = admin.firestore().collection('stats').doc(yearId).collection('months').doc(monthId).collection('days').doc(daysId)

// get all comments and aggregate
return docRef.collection('tickets')
     .get()
     .then(querySnapshot => {

        // get the total comment count
        const tickets = querySnapshot.size       

        // data to update on the document
        const data = { tickets }

        // run update
        return docRef.update(data)
     })
     .catch(err => console.log(err) )

Structure of my firestore

As far as accessing the docs on the query snapshot goes, this answer shows a good way to do that.

In terms of efficiency, instead of looping through and summing each value, you can have a function watch the tickets documents for change.

OnCreate -> might do nothing

OnEdit -> diff the old and new counts get the parent day document, and update the total with the diff in a transaction.

OnDelete -> Similar to OnEdit, just remove the value from the parent day document's total.

You probably are aware but you can use path IDs in the functions to get the required IDs for the parent day doc update.

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