Emiel VdV
Emiel VdV

Reputation: 297

How to add view count in Cloud Firestore?

I am building a post website and I would like to implement the functionality to add a view count to each post. I think it should be considered with my backend, which is Cloud Firestore.

Does anyone know how to do this?

Upvotes: 0

Views: 815

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 1

If you need to increment a counter each time a post is viewed, then you should create a document in which you should add a property of type number like this:

Firestore-root
  |
  --- data (collection)
        |
        --- counters (document)
              |
              --- $postId: 125

The name of the field should be the post ID and the value should be a number. Each time a post is displayed you should simply increment this value. Since you always need to increment the number by one, there is no need to use transactions but an increment operation.

Upvotes: 3

Related Questions