Angular 4 Firebase - Cloud Firestore 'Deeply Nested' vs 'Flatten'

Viewed 845

Curious how to structure the following using "Cloud Firestore (beta)" database

Collections/Entities = 'Menus', 'Pages', 'Columns', 'Sections', 'Items'

Menu has many Pages, Page has many Columns, Column has many Sections, Section has many Items. Would I be correct in structuring this where ...

  • Page doc has menuId
  • Column doc has pageId
  • Section doc has columnId
  • Item doc has sectionId

So for example I would retrieve all menu-pages with..

this.afs.collection('pages', ref => ref.where('menuId', '==', menuId));

all page-columns with..

this.afs.collection('columns', ref => ref.where('pageId', '==', pageId));

Or should I structure this as subcollections?

1 Answers

In NoSQL, your first question is always "How will I query this data from my app?". You have a series of One-to-Many relationships (i.e, page to column), which leads to two main patterns.

  1. Hierarchy (parent-child). If the columns are always queried via the parent doc, nest a subcollection. Then you can grab the collection anytime you have a reference to the parent docpageRef.collection('columns').

  2. Denormalized (sibling). But what if you need to query columns across multiple pages? In that case, you might want to use a root or higher level collection, saving a reference or id to it's sibling-level page. Then you can make queries like afs.collection('columns', ref => ref.where('color', '==', 'orange')), allowing you to query columns without recursing the database tree to find all the subcollections.

Related