【问题标题】:Typescript cloud function to aggregate firestore field value用于聚合 Firestore 字段值的 Typescript 云函数
【发布时间】:2021-10-31 05:32:40
【问题描述】:

我有一个文档,其中有两个字段;

  1. 类别
  2. 以微毫秒为单位的持续时间

Category 可以有多个值,例如 category1、category2 等。

我想计算类别 == category1 的所有文档的持续时间总和。请帮忙查询。

import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'


admin.initializeApp()

export const updateCharts = 
functions.firestore.document('users/{UserId}/count/{uid}')
.onWrite(async(change, _) => await updateStats(change))

async function updateStats (change: 
functions.Change<functions.firestore.DocumentSnapshot>){
const chartRating = change.after.ref.parent

let title = (await chartRating.where('Title', '==', 'Game').get()).size;
//duration

const restaurantRef = chartRating.parent!

console.log('{restaurantRef.path} now has ${Title}')
await restaurantRef.update({
Title: Title,

})

【问题讨论】:

    标签: node.js typescript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    使用查询获取所有文档后,您可以使用reduce() 查找总持续时间:

    let title = await chartRating.where('Title', '==', 'Game').get();
    
    const totalDuration = title.docs.reduce((a, b) => a + b.data()["duration"], 0)
    // Adds 'duration' field of all documents
    

    更便宜的替代方法是从 restaurantRef 读取先前的总数,减去该文档持续时间的旧值并添加更新值。这将只花费 1 次读取和 1 次写入操作,而读取所有文档将花费 N 次读取,其中 N 是匹配的文档数。

    【讨论】:

    • 我已经在我的文档中添加了一个持续时间字段。所以每个文档都有一个带值的持续时间字段。我想获取特定类别的所有持续时间的总和。
    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2021-07-03
    • 2019-04-30
    • 2021-02-13
    相关资源
    最近更新 更多