Firestore按DocRef求和查询失败问题排查及解决
问题已解决
传入的参数应仅为uid,而非引用路径(/users/...),同时我更新了循环逻辑以获取准确结果,目前功能正常。
此前问题描述
我在这个问题上已经绞尽脑汁了,它看起来明明很简单。
这段代码是我构建的一个API调用的一部分,其中包含一个名为userRef的字符串参数。我的目标是在rewards集合中,对满足userRef与集合中存储的文档引用相等的文档,求和其pointsValue的总数值。程序没有报错,但即使移除where子句,结果依然为0,希望能找出问题所在。
文档中的引用存储为DocumentReference类型,而非字符串,pointsValue为整数类型。
补充细节
数据库结构
Firestore数据库结构:pointsValue为数值类型,userRef为文档引用(DocumentReference)类型。
输入参数
示例中我暂时移除了where语句,获取所有pointsValue的值。理想情况是传入字符串类型的userRef参数(例如"9vDyJbZPIBO6mmnG4UvIwGZZW6i2"),再将其转换为文档引用,相关代码已被注释。
输出与网络信息
返回变量totalPointsValue应为所有符合条件的pointsValue的整数求和结果。
import { Firestore } from '@google-cloud/firestore'; export default async function firestoreQuerySum({ collection, projectId, userRef }) { try { const db = new Firestore(projectId && projectId.length > 1 ? { projectId: projectId.trim() } : undefined); // 假设userRef是传入的字符串类型用户ID const userDocRef = db.collection('users').doc(userRef); let query = db.collection(collection).where('userRef', '==', userDocRef); let snapshot = await query.get(); /* let totalPointsValue = 0; snapshot.forEach(doc => { totalPointsValue += doc.data().pointsValue || 0; }); */ const totalPointsValue = snapshot.docs.reduce((total, doc) => { return total + (doc.data().pointsValue || 0); }, 0); return totalPointsValue; } catch(e) { return e; } }
内容的提问来源于stack exchange,提问作者sjordan
相关产品推荐
相关产品推荐

