0

There is a certain int value in the realtime database. I modify it using two different Firebase functions. Suppose now it is 500 and both of these functions have been called. One should add 100 to the value, the other - 20. I get the current value from the database (500) in each function and add the corresponding value to it, then write the new value to the database. If I understand correctly, then I will lose one of the values ​​and in the database I will have the value that was last recorded (600 or 520). How can this be avoided?

1 Answers1

1

What you're describing requires that you use a transaction, or the recently added increment() operation.

From Cloud Functions you'll be using the Firebase Admin SDK for Node, where this can be as simple as:

ref.set(firebase.database.ServerValue.increment(100));

And

ref.set(firebase.database.ServerValue.increment(-20));

Also see my answer comparing the performance of both operations: How quickly can you atomically increment a value on the Firebase Realtime Database?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807