firestore update counter for new document

Viewed 123

since firebase (firestore) does not offer any easy and non expansive solution to count the documents in a collection I plan to create several counters to keep track of the number of documents. I have the following setup:

[collection] - [document] - [subcollection]
users          userid       profile
admin          counters

My idea is to create another document "counters" in the collection "admin" and to update the field "profile_created" everytime a new userid document was created.

I see only one problem. If more than one person will create a profile (which created the userid) at the same time, the read/write process will not work since the several persons will get the same number (read) and will all add +1 to this number. Which means instead of several +1's I will have only one +1...

For example: profile_created = 5

5 people register at the same time

All 5 people will get (read) the current counter number (profile_created = 5) All 5 people will add +1 to the counter

The result will be not 11 as I want it to be, i will be 6 since since the different reads will overwrite the others...

Is there any solution to this problem?

Thanks!!!

1 Answers

Firestore has the ability to reliably increment a value. If you trust your users to increment the number, it could be as simple as:

firebase.firestore().collection('counters').doc('profiles')
  .update({
    total: firebase.firestore.FieldValue.increment(1)
  });

Otherwise create a Cloud Function that executes on each Firestore update to increment that value using Firebase Admin.

Related