0

My Firestore structure looks like this:

users > {User} > categories > Gas > transactions > {Transaction {amount: 42.00}}

I want to get all the Categories and the Transactions underneath.

What's the best way in doing that with Firestore?

To get the categories and for each get the Transactions underneath with a further query? Doesn't sound very optimal?

I have to make sure the query path is using the users id so people can't read other peoples data.

Sebastian Patten
  • 7,157
  • 4
  • 45
  • 51
  • I would change the structure; Have a top level collection called Expenses and then each document underneath would have fields for the users uid, the type (Gas, Entertainment, Tools, etc) and then transaction detail. Then, you can easily query for all a users expenses, or a particular type of expense and all users can read each others data. I think that satisfies the criteria in the question. Then you can also query for all users Gas expense with one query. – Jay Apr 10 '23 at 17:23
  • I followed Frank and Renaud's advice. I'd post my Firebase configurations here to help the next person, but my question got closed :D – Sebastian Patten Apr 11 '23 at 11:18

1 Answers1

1

All read operation in Firestore are shallow. So reading a category in your data model will never read transactions.

The closest you can get is to use one read operation to read all categories, use a collection group query to read all transactions for all categories, and then put them all in groupings you need client-side. You can find the parent document of each transaction snapshot by getting its reference and then walking up the chain of parent properties.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks! How would you re-associate them with their parent categories? Does each item have a parent id reference or something similar? – Sebastian Patten Apr 09 '23 at 17:43
  • 3
    @SebastianPatten Have a look at this [answer](https://stackoverflow.com/a/61014467/3371862) which explains how to get the parent docs IDs, but note that you’ll need to query these parent docs if you want to get their data. Another approach is to save, in the child docs, the desired fields from their parents. – Renaud Tarnec Apr 09 '23 at 18:49