Elia Weiss
Elia Weiss

Reputation: 9886

Cloud Firestore , nodejs (cloud functions), synchronize access

What is the Java equivalent of 'synchronize' in Firestore, nodejs (cloud functions)?

Suppose I keep a counter in the db and I want to increment it by 1, so I have to read the value, increment it, and store it back.

How do I make sure the counter value didn't change by other party, between the read and write action?

Upvotes: 0

Views: 144

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

How do I make sure the counter value didn't change by other party, between the read and write action?

There are two ways in which you can solve this problem.

The first one would be to use a transaction, which is an operation where you read a value from a document, you increment it and then write the document back.

The second solution would be to use the FieldValue.increment(50) operator:

An increment operation increases or decreases the current value of a field by the given amount. If the field does not exist or if the current field value is not a numeric value, the operation sets the field to the given value.

If you need at some point in time to decrement a value, simply pass a negative value to the increment() function:

Upvotes: 3

Related Questions