繁体   English   中英

如何使用Firebase函数从文档中查询数字并将其总和成Firestore中的父文档

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

我有一个文档集合,并且我有一个功能,可以对每个文档进行计数并将计数保存到父文档中,并且每次创建新文档时都会更新。 我想查询该字段并将其添加到其父文档中以对其进行汇总。 我需要帮助,想出一个代码来查询不同文档中的所有字段并将其汇总到父文档中

这是我的代码,它计算每个文档并将其保存为文档字段

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) )

我的消防站的结构

就访问查询快照上的文档而言, 此答案显示了一种很好的方法。

在效率方面,您可以让函数监视票证文档是否有更改,而不是遍历和求和每个值。

OnCreate->可能什么都不做

OnEdit-> diff的新旧计数将获取父日文档,并在事务中使用diff更新总数。

OnDelete->与OnEdit类似,只需从父日文档的总计中删除值即可。

您可能已经知道了,但是您可以在函数中使用路径ID来获取父级文档更新所需的ID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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