Home > database >  How to count how many times document was downloaded in Firebase?
How to count how many times document was downloaded in Firebase?

Time:05-08

I have a collection in my Firestore Database with posts. Each post has some comments as a document in the collection comments in the main post document (screenshot)enter image description here

In my Android app when I click on the post item I go to PostDetail screen and there I download comments. I want to increment the value of timesViewed for each comment which has been downloaded and displayed.

Is it possible to do that? I want to do that in the most efficient way. I don't want to increment every single comment manually by sending a request timesViewed .

CodePudding user response:

I want to increment the value of timesViewed for each comment which has been downloaded and displayed.

If you're looking for something that does that automatically, please note that there is nothing built-in.

Is it possible to do that?

Yes, but you should implement your own mechanism.

I don't want to increment every single comment manually by sending a request timesViewed .

Unfortunately, there is no other way. However, it is very easy to implement. You can use FieldValue.increment(1).

CodePudding user response:

Unfortunately, such a feature does not exist in the RealtimeDatabase firebase and firestore to automatically increase a field. But you can create a counter and retrieve the counter every time onResponse () or onComplete and increase it by 1, which is not recommended for 2 reasons.

  1. Generates extra traffic, especially if the number of users is large
  2. It is not reliable because someone can intentionally increase it

But if you do not mind a lot of traffic and you insist on doing so, do not forget to set rules in the firebase console to control the incremental frequency.

  • Related