我想在用户采取行动时奖励用户。它可能发生在他的“硬币”之路上尚未存在。这就是我收到错误的原因:
交易失败:错误:XXX的数据不存在。
如何在路径不存在的情况下运行事务?这就是我试过的:
exports.facebookShared = functions.firestore.document('facebookShared/{randomUID}').onCreate(event => {
const data = event.data.data()
const uid = data.uid
var promises = []
promises.push(
db.collection('facebookShared').doc(event.data.id).delete()
)
const pathToCoins = db.collection('users').doc(uid).collection('server').doc('server')
promises.push(
db.runTransaction(t => {
return t.get(pathToCoins)
.then(doc => {
var newCoins = 0
if (doc.data().hasOwnProperty("coins")){
newCoins = doc.data().coins + awardFacebookShare.coins
}
t.update(pathToCoins, { coins: newCoins });
});
})
.then(result => {
console.log('Transaction success', result);
})
.catch(err => {
console.log('Transaction failure:', err);
})
)
return Promise.all(promises)
})
答案 0 :(得分:0)
我遇到过这些文档:https://cloud.google.com/nodejs/docs/reference/firestore/0.8.x/Firestore#runTransaction
该文档比这里更好:https://firebase.google.com/docs/firestore/manage-data/transactions
以下代码有效:
exports.facebookShared = functions.firestore.document('facebookShared/{randomUID}').onCreate(event => {
const data = event.data.data()
const uid = data.uid
var promises = []
promises.push(
db.collection('facebookShared').doc(event.data.id).delete()
)
const pathToCoins = db.collection('users').doc(uid).collection('server').doc('server')
promises.push(
db.runTransaction(t => {
return t.get(pathToCoins)
.then(doc => {
var newCoins = awardFacebookShare.coins
if (doc.exists){
if (doc.data().hasOwnProperty("coins")){
newCoins += doc.data().coins
}
t.update(pathToCoins, { coins: newCoins });
return Promise.resolve(newCoins);
}else{
t.create(pathToCoins, { coins: newCoins });
return Promise.resolve(newCoins);
}
});
})
.then(result => {
console.log('Transaction success', result);
})
.catch(err => {
console.log('Transaction failure:', err);
})
)
return Promise.all(promises)
})