-1

I want to get subscriptions of users.
I can get user one by one then get each user subscriptions.
But this will make many document reads.
i want to get subscriptions 10 by 10 sorted by newest.
is that possible?

Firestore path

Mahdi h
  • 13
  • 4

2 Answers2

1

we can get users one by one then get each user subscription but this will make many reads

It doesn't matter if you get the documents one by one, or all documents at once, you'll always pay the same price. What I mean is that if you perform a query that returns 5 documents, you'll have to pay 5 read operations. If you read each of those 5 documents, one by one, the same number of read operations you have to pay.

I want to get subscriptions 10 by 10 sorted by newest is that possible?

In that case, you have to perform a query. For that, I recommend you start with the official documentation.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • getting the 5 newest subscriptions directly will be 5 reades but mapping through users to find the new subcollection will cost so much more especially if there are so many users. – Mahdi h Nov 30 '21 at 15:01
  • I'm not sure I understand. But each document that is returned by a query will cost you one read operation. You cannot change that, So if you need to limit the number of documents that a query returns, you should consider adding a `.limit(n)` call, right? – Alex Mamo Nov 30 '21 at 15:15
  • user/userId/subscriptions this is the path of the collection. my question is how to get the 5 newst subsubscription ? – Mahdi h Nov 30 '21 at 15:34
  • In that case, you should a [collectionGroup](https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query) Query. In that way, you can read the documents that exist within the **all** `subscriptions` subcollections. Give it a try and tell me if it works. – Alex Mamo Nov 30 '21 at 15:50
  • request : const querySnapshot = await getDocs(collectionGroup(db, `subscriptions`)); rule: match /users/{users}/subscriptions/{subscriptions} { allow read; allow write; } i tried it but i get this problem Uncaught (in promise) FirebaseError: Missing or insufficient permissions. – Mahdi h Nov 30 '21 at 16:25
  • Have you set the proper security rules? If you get that message, probably not. Make sure you have the correct rules, as well as the correct index. – Alex Mamo Nov 30 '21 at 17:24
  • Hello Alex yes thanks a lot also i solved the rull problem. i did it like that in the beginning:match /subscriptions/{subscriptions}. but it should be like that: match /{path=**}/subscriptions/{subscriptions}. Thanks a lot – Mahdi h Dec 01 '21 at 18:09
0

Subcollections: Firestore query subcollections

Pagination: https://firebase.google.com/docs/firestore/query-data/query-cursors

Be aware that asking questions in this way lowers the chances of getting answers.

Heikkisorsa
  • 740
  • 9
  • 31