我正在根据交易中第三方服务的结果尝试更新多个Firestore文档。问题是,我收到以下错误:
错误:无法修改已提交的WriteBatch。
这是我的代码:
export default async function debitDueTransactions(context: any) {
const now = new Date().getTime();
return db.runTransaction(async (transaction: FirebaseFirestore.Transaction) => {
const chargesToCaptureRef = db.collection(`charges_to_capture`)
.where('dateToCapture', '>=', now)
.where('dateToCapture', '<=', (now + 86400000))
.where('captureResult', '==', null);
return transaction.get(chargesToCaptureRef).then((chargeToCaptureQuerySnap: FirebaseFirestore.QuerySnapshot) => {
chargeToCaptureQuerySnap.forEach(async (doc: FirebaseFirestore.QueryDocumentSnapshot) => {
const chargeToCapture = <ChargeToCapture>doc.data();
chargeToCapture.id = doc.id;
let errorKey = null;
// Calling third party service here, waiting response
const captureResult = await captureCharge(chargeToCapture.chargeId).catch((error: any) => {
errorKey = error.code ? error.code : 'unknown_error';
});
transaction.update(doc.ref, { captureResult: captureResult, errorKey: errorKey });
});
return new Promise((resolve) => { resolve(); });
})
});
}
知道我做错了什么吗?
答案 0 :(得分:0)
从API文档中可以看到,transaction.get()仅接受DocumentReference类型的对象。您正在向它传递一个Query对象。 Firestore事务无法在查询上进行交易。如果要处理从查询返回的所有文档,则应在事务之前执行查询,然后在每个DocumentReference上分别使用transaction.get()。