How to increment existing number field in Cloud Firestore

前端 未结 2 1751
长情又很酷
长情又很酷 2020-12-30 23:17

I have a field which indicates the number of transactions. I would like to increment it by 1 as soon as a transaction occurs. I could\'nt find any method to dir

相关标签:
2条回答
  • 2020-12-30 23:33

    You should write a cloud function that listens to the transaction, then increase the index.

    https://firebase.google.com/docs/functions/

    0 讨论(0)
  • 2020-12-30 23:52

    Firestore now has a specific operator for this called FieldValue.increment(). By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.

    From the Firebase documentation on incrementing a numeric value:

    var washingtonRef = db.collection('cities').doc('DC');
    
    // Atomically increment the population of the city by 50.
    washingtonRef.update({
        population: firebase.firestore.FieldValue.increment(50)
    });
    

    So this example increments the population by 50, no matter what is current value is. If the field doesn't exist yet (or is not a number), it is set to 50 in this case.

    0 讨论(0)
提交回复
热议问题