![](/img/trans.png)
[英]How do to retrieve all documents in a collection and see if a document exists in 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.