You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript编写Cloud Function实现Firestore Title等于Game的过滤计数

修改方案

你只需要在现有计数器的累加逻辑前新增Title字段值匹配规则即可,以下提供两种实现方案:

方案1:最小修改适配原有逻辑

仅调整循环内的判断条件,仅当文档Title字段等于Game时累加计数器:

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 = 0

  const docRefs = await chartRating.listDocuments()
  for (const docRef of docRefs) {
    const snapshot = await docRef.get()
    const data = snapshot.data()
    // 新增Title等于Game的判断条件
    if (data !== undefined && data.Title === 'Game') {
      Title++
    }
  }

  const restaurantRef = chartRating.parent!
  // 修复原代码模板字符串不生效的问题,把单引号改为反引号
  console.log(`${restaurantRef.path} now has ${Title}`)
  await restaurantRef.update({
    Title: Title,
  })
}

方案2:性能优化版本(推荐)

无需全量拉取集合下所有文档,直接通过Firestore的条件查询过滤出符合要求的文档,数据量较大时可以大幅提升函数执行效率:

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
  // 直接用where条件过滤,仅查询Title等于Game的文档
  const gameTitleSnapshot = await chartRating.where('Title', '==', 'Game').get()
  const Title = gameTitleSnapshot.size

  const restaurantRef = chartRating.parent!
  console.log(`${restaurantRef.path} now has ${Title}`)
  await restaurantRef.update({
    Title: Title,
  })
}

注意:如果你的Firestore中Title字段存储的Game值有大小写差异(比如全小写game、首字母小写game),需要调整判断条件中的字符串和实际存储值保持一致。

内容的提问来源于stack exchange,提问作者akhicoda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:48:03