gpt4 book ai didi

google-cloud-firestore - 云函数 : Transaction with FieldValue. increment() 未以原子方式运行

转载 作者:行者123 更新时间:2023-12-04 04:21:30 25 4
gpt4 key购买 nike

我有一个 Cloud Functions 事务,它使用 FieldValue.increment() 来更新嵌套映射,但它不是以原子方式运行,因此值更新不准确(快速连续运行事务会导致计数不正确)。

该函数是通过以下方式触发的:

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));

Example:

Value of field to increment: 0

Tap on button that performs the function multiple times in quick succession (to switch between true and false for "Published")

Expected value: 0 or 1 (depending on whether reference document value is true or false)

Actual value: -3, 5, -2 etc.

As far as I'm aware, transactions should be performed "first come, first served" to avoid inaccurate data. It seems like the function isn't "queuing up" correctly - for lack of a better word.



我有点难住,非常感谢任何有关此的指导。

最佳答案

哦,天哪,我错过了返回......

return db.runTransaction(tx => {

关于google-cloud-firestore - 云函数 : Transaction with FieldValue. increment() 未以原子方式运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59159453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com