我正在尝试创建Firebase函数,以将子集合从一个用户克隆到另一个用户。
但是,我在最后一步遇到了问题:向新用户添加子集合文档。
这是我的功能:
import { Firestore } from '@google-cloud/firestore';
exports.handler = async function(req: any, res: any, db: Firestore) {
const fromUid = req.body.from;
const toUid = req.body.to;
let transactionCount = 0;
const userToRef = await db
.collection('users')
.doc(toUid)
.collection('transactions');
await userToRef.add({ ...{ data: 'some-dummy-data' } }); // At this point I get write to the collection
const transactions = await db
.collection(`users/${fromUid}/transactions`)
.get();
const transactionsList: any[] = [];
transactions.forEach((doc: any) => {
const transaction = doc.data();
transaction.uid = toUid;
transactionsList.push(transaction);
userToRef.add({
// Here write to the collection doesnt work
...transaction
});
transactionCount++;
});
console.log(transactionsList);
res.send(
`Successfully cloned ${transactionCount} transactions from ${fromUid} to ${toUid}.`
);
return '';
};
在上面的代码示例中,我对用户子集合进行了两次写入(请参见代码注释)。第一个工作正常,第二个工作不正常。
有什么主意我为什么不能在forEach循环中编写代码?
答案 0 :(得分:3)
您应该使用Promise.all()
,以便在通过userToRef
对象将响应发送回客户端之前,等待对res
集合的所有写操作完成。
以下改编的代码应该可以工作(未经测试)。
但是,由于我不知道如何调用此函数(您可能是从Cloud Function本身调用它的),因此我不清楚您到底应做些什么。您可能不需要执行return '';
,因为执行res.send
()实际上是在终止函数。供您参考,我在下面添加了经过测试的HTTPS Cloud Function的完整代码,该代码执行一组类似的集合写操作。
exports.handler = async function (req: any, res: any, db: Firestore) {
const fromUid = req.body.from;
const toUid = req.body.to;
let transactionCount = 0;
const userToRef = await db
.collection('users')
.doc(toUid)
.collection('transactions');
await userToRef.add({ ...{ data: 'some-dummy-data' } }); // At this point I get write to the collection
const transactions = await db
.collection(`users/${fromUid}/transactions`)
.get();
//const transactionsList: any[] = [];
const promises: Promise<DocumentReference>[] = [];
transactions.forEach((doc: any) => {
const transaction = doc.data();
transaction.uid = toUid;
//transactionsList.push(transaction);
promises.push(
userToRef.add({
// Here write to the collection doesnt work
...transaction
}));
transactionCount++;
});
//console.log(transactionsList);
await Promise.all(promises);
res.send(
`Successfully cloned ${transactionCount} transactions from ${fromUid} to ${toUid}.`
);
//return '';
};
这是HTTPS Cloud Function的代码,它实现了一组类似的集合写操作:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { DocumentReference } from '@google-cloud/firestore';
admin.initializeApp();
export const helloWorld = functions.https.onRequest(async (req, res) => {
const db = admin.firestore();
let writeCount = 0;
const theArray: string[] = ['AA', 'BB', 'CC'];
const promises: Promise<DocumentReference>[] = [];
theArray.forEach((value: string) => {
promises.push(db.collection('testCollection').add({ val: value }));
writeCount++;
});
await Promise.all(promises);
res.send(`Successfully wrote ${writeCount} documents.`);
});