0

I am learning Firebase after many years of using SQL RDBMSs. This is definitely a challenge.

Say, I have a collection of objects. Each object can belong to any number of categories. Categories have user-editable labels (e.g. user may rename the label after the fact.

SQL RDBMS

So, in RDBMS I would have:

Object table -> { object_id, ... }

Category table -> { category_id, label, ... }

ObjectCategory -> { object_id, category_id }

I see the following options to implement this in Firebase:

1. Objects collection with category label arrays in objects:

/user/objects -> [{ object_id, categories: [ 'category_label1', 'category_label2' ] }, ... ]

Seems yucky. Renaming/deleting a category will mean updating all the objects.

2. Objects referring categories by id

/user/objects -> [{ object_id, categories: [ 'category_id1', 'category_id2' ] }, ... ]

/user/categories -> [{category_id, label, is_deleted: false}, ...]

This seems more reasonable and maintainable. Except sometimes (I think pretty rarely) there will be 2 queries.

3. Collection of object and object categories

/user/objects -> [{object_id1, ...}, {object_id2, ...}]

/user/object_id1/labels -> [{categorylabel1}, {categorylabel2}]

This is largely comparable to option 1 but requires less churn on object documents and makes updates smaller. Renaming/deleting a category becomes a pain.

So, what is the recommended approach?

Eugene
  • 9,242
  • 2
  • 30
  • 29
  • In the NoSQL world, we are usually structuring a database according to the queries that we want to perform. What are those queries? – Alex Mamo Aug 19 '22 at 07:30
  • @AlexMamo 1. Get all categories for an object. 2. Get objects in categories. 3. (for UI) get all categories – Eugene Aug 19 '22 at 16:15
  • Is any of the presented structures return the desired documents? – Alex Mamo Aug 20 '22 at 07:52
  • (1) and (3). But I think I am getting your point and sounds like (1) is the best fit. – Eugene Aug 21 '22 at 17:09
  • Any structure that can be queried, and can bring the desired results, can be used in your project. However, try not to think in SQL terms. In NoSQL, there is no [the best database structure](https://stackoverflow.com/questions/53053768/what-is-the-correct-way-to-structure-this-kind-of-data-in-firestore). – Alex Mamo Aug 21 '22 at 17:42

0 Answers0