I guess firebase is not a big fan of nesting but they also say (if I understood correctly) that one-level nesting is okay.
Let's have an example of a restaurant and 2 diff scenarios:
Flat: No Nesting (no subcollections)
/restaurants
-mealCategoriesID: List<DocumentReference>
-mealsID: List<DocumentReference>
/meal_categories
/meals
-mealCategoryID: DocumentReference
Deep: Nesting
/restaurants/meal_categories/meals
So, what would be the best approach in this restaurant example?
When it comes to NoSQL data modeling there is no singular "best" model. It all depends on how you want to use that data.
Before Firestore supported collection group queries it often made sense to store items in a few top-level list, so that you could query over them. That would've been your first model, which would've always allowed you to query all meals, no matter what restaurant or category.
But with collection group queries, you can now always query all meals, since they're in collections of the same name. And at this stage, spreading them out across multiple subcollections actually helps write throughput, since those subcollections are more likely to be spread out across the disks.
One thing that sets your models apart is the ability to query across meals of a certain category.
Say you want a query across all restaurants for meals of a specific category. In your last model that is only possible if you also store the category ID in each meal document.
Similarly, say that you want to query across the meals for a specific restaurant, or a subset of restaurants, for meals of a certain category. To allow such queries, each meal needs to have a category ID and a restaurant ID field.
In both the cases above you're duplicating data, to allow certain queries. But it's still usually better to perform some nesting, since it allows for better write concurrency/throughput if you ever reach usage volume where this matter.
Note that the read and query performance is the same for each data model, since Firestore only allows use-cases where it can guarantee that performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With