如何在Firestore中增加字段



我正在尝试实现一个用于支付目的的计数器。现在我正在贝宝的取消状态下测试它,而不是实际购买,因为我现在没有证书。一旦我这样做,我将把大部分代码转移到实际的支付成功功能上。

有没有一种方法可以通过增加现有的int字段来更新firebase文档的int字段?

我这里的代码进入了一个无限循环,因为它跟踪自己的数据。

paymentCancelled: function(data) {
console.log("payment cancelled")
let db = firebase.firestore()
db.collection("users").where("userId", "==", firebase.auth().currentUser.uid)
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log("before: " + doc.data().credits)
//this is where I'm having trouble
const creditIncrement = doc.data().credits + 100
var creditRef =
db.collection("users").doc(firebase.auth().currentUser.uid);
return creditRef.update({
credits: creditIncrement
})
.then(function() {
console.log("Document successfully updated!");
return;
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
})
})
console.log(data) //logging out contents from PayPal, unnecessary atm
}

您应该使用.get()而不是. onSnapshot()

db.collection("users").where("userId", "==", firebase.auth().currentUser.uid)
.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log("before: " + doc.data().credits)
//this is where I'm having trouble
const creditIncrement = doc.data().credits + 100
var creditRef =
db.collection("users").doc(firebase.auth().currentUser.uid);
return creditRef.update({
credits: creditIncrement
})
.then(function() {
console.log("Document successfully updated!");
return;
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
})
})

.get()只获取一次数据,而不是用onSnapshot监听数据变化

为了数据一致性,您可能需要考虑使用firestore事务

最新更新