Google cloud firestore 云函数:具有FieldValue.increment()的事务未以原子方式运行
我有一个云函数事务,它使用FieldValue.increment()更新嵌套映射,但它不是原子运行的,因此值更新不准确(快速连续运行事务会导致不正确的计数) 该功能通过以下方式启动:Google cloud firestore 云函数:具有FieldValue.increment()的事务未以原子方式运行,google-cloud-firestore,google-cloud-functions,Google Cloud Firestore,Google Cloud Functions,我有一个云函数事务,它使用FieldValue.increment()更新嵌套映射,但它不是原子运行的,因此值更新不准确(快速连续运行事务会导致不正确的计数) 该功能通过以下方式启动: export const updateCategoryAndSendMessage= functions.firestore.document('events/{any}').onUpdate((event, context) => { 其中包括以下交易: db.runTransaction(tx =&g
export const updateCategoryAndSendMessage= functions.firestore.document('events/{any}').onUpdate((event, context) => {
其中包括以下交易:
db.runTransaction(tx => {
const categoryCounterRef = db.collection("data").doc("categoryCount")
const intToIncrement = event.after.data().published == true ? 1 : -1;
const location = event.after.data().location;
await tx.get(categoryCounterRef).then(doc => {
for (const key in event.after.data().category) {
event.after.data().category[key].forEach(async (subCategory) => {
const map = { [key]: { [subCategory]: FieldValue.increment(intToIncrement) } };
await tx.set(categoryCounterRef, { [location]: map }, { merge: true })
})
}
},
).then(result => {
console.info('Transaction success!')
})
.catch(err => {
console.error('Transaction failure:', err)
})
}).catch((error) => console.log(error));
例如:
要递增的字段值:0
快速连续点击多次执行该功能的按钮(在“已发布”的“真”和“假”之间切换)
期望值:0或1(取决于参考文档值是否为真)
实际值:-3、5、-2等
据我所知,交易应该“先到先得”,以避免数据不准确。似乎函数没有正确地“排队”——因为没有更好的词
我有点不知所措,非常感谢您的指导。哦,天哪,我错过了返回
return db.runTransaction(tx => {
我认为错误消息与您的交易无关。如果你在谷歌上搜索该邮件,你会看到其他人也有同样的问题,但他们没有处理事务。@DougStevenson对此表示感谢,我能够解决凭证问题(添加到解决方案的链接)。不幸的是,该事务仍然没有进行原子更新。您可能希望更新该问题,以删除对现已解决的错误的提及(因为它不再是一个问题),而是关注您对该事务的观察细节。@DougStevenson Sure,我已经做了,如果你能提供一些函数实际执行的具体细节,那会很有帮助,这与你所期望的不同。