I'm trying to create a Firebase function that clones a subcollection from one user to another.
However, I'm having a problem with the last step: Adding subcollection documents to the new user.
Here is my function:
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 '';
};
In the code example above I'm doing two writes to the user subcollection (see code comments). First one is working OK and the second one is not.
Any idea why I cannot do write inside a forEach loop?