我写这篇文章是因为我的计划云功能遇到了一些问题。
步骤1:访问以下/collection:users=>doc:uid=>收款:银行=>doc:账户。
第二步:每24小时将我的用户(所有用户(每日RewardCounter增加150。
问题是,我的函数无法访问用户的集合uid并返回错误,因为计划函数无法读取uid(参见图片(。
问题: 你知道我如何根据每个用户的个人"uid"访问他们的子集合,以在集合"bank"中添加150吗
在此处输入图像描述
export const dailyCreditReinitialize = functions.pubsub.schedule('0 0 * * *').onRun(async (context) => {
const uid = context.auth!.uid; // seems like the function does not read that
const userRef = db.collection('users').doc(uid);
const userSnap = await userRef.get();
const getUid = userSnap.data()!.uid;
const bankCollectionRef = db.collection('users').doc(getUid).collection('bank');
return bankCollectionRef.get()
.then(querySnapshot =>{
if (querySnapshot.empty){
console.log("Nothing to return")
return null;
} else {
let batch = db.batch();
querySnapshot.forEach(doc => {
batch.update(doc.ref, {
dailyRewardCounter: 150,
});
});
return batch.commit();
}
})
.catch(error => {
console.log(error);
return null;
});
})
与实时数据库触发的云函数相反,对于调度的云函数,context.auth
为null。
如果我正确理解你的问题("增加我的用户(所有用户("(您需要循环遍历集合的所有用户文档。伪代码中的一些内容如下:
- 循环用户集合并获取所有用户ID
- 对于每个用户,获取
bank
集合的querySnapshot - 在每个querySnapshots上循环以更新银行文档