1

I have the following test data where a single test-course has three units which each has multiple subunits.

enter image description here

I am able to retrieve all subunits in one unit at a time using react-firebase-hooks like below:

const [units, loading, error] = useCollection(
    session && query(collection(db, "courses", "test-course", "unit-1"))
  );

However, is there a way to fetch all units & subunits under a test-course? My goal is to render all of those units and subunits like this screenshot.

Or is there a better way to structure this data? Previous methods I thought of were:

  • putting all subunit objects in one collection; but this seemed unintuitive as I need to track data/progress for each unit independently from one another

enter image description here

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Tyler Kim
  • 181
  • 1
  • 11
  • If you want to load the documents from all units under a given question, you can use the approach samthecodingman showed here: https://stackoverflow.com/questions/68049541/collectiongroupquery-but-limit-search-to-subcollections-under-a-particular-docum/68049847#68049847 – Frank van Puffelen Aug 11 '23 at 13:19

1 Answers1

1

Since you mention "under a single document" in the question title, I make the assumption that you want to display the data for one course at the time (test-course in your example). If this is correct you have two options:

Option 1: Execute X queries (X = 3 in your example)

You execute a query for each unit Document and you merge the results in the front end

Option 2: Denormalize data (i.e. duplicate data)

You put all subunit Documents in one collection, as you mentioned, and you add the parent unit value as a field in each subunit document. This way you can sort the subunit documents per unit and display them under the correct unit category.

You can also execute a query that filters the collection based on the unit value, in order to the subunits of one unit (or several units with the in operator)

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121