我正在尝试在Cloud函数中运行事务以遍历数组以增加Cloud Firestore中用户的crowns
字段。该交易目前仅适用于第一个用户,而不适用于后续用户(或DocumentReferences)
我尝试更改.runTransaction
部分的回报,还尝试更改某些承诺。我使用https://firebase.google.com/docs/firestore/manage-data/transactions作为参考。
exports.crowns_job =
functions.pubsub.topic('comments-tick').onPublish((event) => {
var uids = [];
var uids1 = [];
//var crownVal = 0;
admin.firestore().collection('winners').get().then(function(querySnapshot) {
if (querySnapshot.size > 0) {
// Contents of first document
//console.log(querySnapshot.docs[0].data());
for (i = 0; i < querySnapshot.size; i++){
if (querySnapshot.docs[i].id != "uids"){
uids[i] = querySnapshot.docs[i].data().uid; //new individual uids from winners
console.log(uids)
console.log("holyyyy" + querySnapshot.docs[i].data().uid)
}
}
admin.firestore().doc('winners/uids').get().then(function(doc) {
if (doc.exists) {
uids1 = doc.data().uids //old uids
console.log("uids///" + uids)
uids.sort()
uids1.sort()
for (i = 0; i < uids.length; i++){
console.log("here")
console.log(`uids is ${uids[i]} and uids1 is ${uids1[i]}`)
if (uids[i] == uids1[i]){
return admin.firestore().runTransaction(function(transaction) {
sfDocRef = admin.firestore().doc('users/'+uids[i])
// This code may get re-run multiple times if there are conflicts.
transaction.get(sfDocRef).then(function(sfDoc) {
if (!sfDoc.exists) {
throw "Document does not exist!";
}
var newCrowns = sfDoc.data().crowns + 1;
return transaction.update(sfDocRef, { crowns: newCrowns });
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});
}
}
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
});
admin.firestore().doc('winners/uids').update({
uids: uids
});
} else {
console.log("No such document!");
}
});
console.log("This job is run every 5 minutes!");
});