[英]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) )
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 OnCreate->可能什么都不做
OnEdit -> diff the old and new counts get the parent day document, and update the total with the diff in a transaction. OnEdit-> diff的新旧计数将获取父日文档,并在事务中使用diff更新总数。
OnDelete -> Similar to OnEdit, just remove the value from the parent day document's total. OnDelete->与OnEdit类似,只需从父日文档的总计中删除值即可。
You probably are aware but you can use path IDs in the functions to get the required IDs for the parent day doc update. 您可能已经知道了,但是您可以在函数中使用路径ID来获取父级文档更新所需的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.