Reputation: 5279
I am wondering if I am modelling my Firestore data models correctly as I realise the current way will result in a lot of requests to the server.
Context:
I have a exercises
collection.
{
exercises: {
abc123: {
name: "Squat",
vidUrl: 'https://example.com'
},
bcd234: {
name: "Push Up",
vidUrl: 'https://example.com'
}
}
}
And I have a workouts
collection. When I load a specific workout, I am looping through and loading the individual step exercises and mapping them to the original response.
{
workouts: {
uniqueId: {
name: 'Strength',
circuits: [{
steps: [
{
duration: 45,
exerciseId: 'abc123'
},
{
duration: 30,
exerciseId: 'bcd234'
}
]
}]
}
}
}
Is this the best way of doing this? Or should I be mapping the exercise data to the steps in the first place?
Also, does this modelling of data result in difficulty updating a circuits.steps
because it is a nested array?
Upvotes: 1
Views: 180
Reputation: 138834
I realise the current way will result in a lot of requests to the server.
Queries in Firestore are shallow, which means they only get items from the collection that the query is run against. There is no way to get documents from two top-level collection in a single query. So in your case, you need to query your database twice, once to get each exerciseId
from the steps
array and second, based on that id, you need to get each particular exercise.
According to the official documentation regarding usage and limits, everything in Firestore it's about the number of reads and writes.
According to your comment:
for each exerciseId in the
steps
array in the workouts collection, I am querying to get each exercise.
To reduce the number of reads you can host beneath your steps
array the entire exercise
object. This means that you need to query the database only once because everything that you need is already there. This practice is called denormalization
and is a common practice when it comes to Firebase. If you are new to NoQSL databases, I recommend you see this video, Denormalization is normal with the Firebase Database for a better understanding. It is for Firebase realtime database but same rules apply to Cloud Firestore.
Also, when you are duplicating data, there is one thing that need to keep in mind. In the same way you are adding data, you need to maintain it. With other words, if you want to update/detele an exercise, you need to do it in every place that it exists.
Upvotes: 1