1

I have a firestore structure for a collection called 'chartites' containing categories with records. The structure is the following:

Collection(Charities) -> Document("categories") -> Collection(Records) -> Document(ID) -> fields (with data) enter image description here

My question is:

How do I get the fields for a given ID, without querying each category (document), with a "single" query.

I.e.: I want to retrieve the data for the record (document) with ID: FC9tH5rABCsqh5kunMND (top of the list for the charity category 'animals')

I have tried to do: db.collection('charities').where('id', '==', 'FC9tH5rABCsqh5kunMND') - but can't seem to make this work.

Perelan
  • 396
  • 5
  • 19

2 Answers2

3

You can't. Firestore queries are shallow, meaning they only consider documents of a single collection. They don't ever consider documents in subcollections. If you want the documents in subcollections, each subcollection will require its own query.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Plus, if you auto-generate IDs in the subcollections, there is no guarantee that it will be unique across the main collection. – technophyle Jan 27 '20 at 19:02
  • Thanks for the input @Doug Stevensen. Is that real? How do I ensure for unique IDs across the database @technophyle? – Perelan Jan 27 '20 at 21:16
  • 1
    It is real. @technophyle the chances of any two automatically generated IDs colliding is astronomically low (unless your operating system's random number generator is fantastically broken). If you're worried about that, you might also be worried about the universe imploding suddenly. :-) – Doug Stevenson Jan 27 '20 at 21:22
  • Gonna add this: https://stackoverflow.com/questions/46573014/firestore-query-subcollections – KdgDev Aug 13 '20 at 19:03
1

If by-id is the primary way you want to access your data, you could restructure it so that it's stored by ID, with fields in each ID for which charities are associated with it. Then you could still get categorical information about, say, " animals " by querying all the ids where the category field includes animals.

ultraGentle
  • 5,084
  • 1
  • 19
  • 45
  • Are you meaning that I should for each record (entity) store the category within the field? You are right! I just came to think I then can do where("category", "==", "animal") - This will then remove the "amazing nesting" of documents/collections. – Perelan Jan 27 '20 at 21:19
  • Exactly! Sometimes restructuring around is the way to go. – ultraGentle Jan 28 '20 at 01:52