0

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++.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Wafi_ck
  • 1,045
  • 17
  • 41

2 Answers2

1

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.

1

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).

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Such a mechanism extremely increases my billable metrics and usage in Firebase right? 1 FieldValue.increment() = 1 request to Firebase ? – Wafi_ck May 08 '22 at 09:03
  • Yes, it does and that's correct. When you increment that field, you have to pay one document write. – Alex Mamo May 08 '22 at 09:15
  • 1
    Okay thanks for the answer. I guess I have to give up this idea :) – Wafi_ck May 08 '22 at 09:19