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
相关产品推荐
相关产品推荐

