I have an application where I have three usertypes: \"The school\", \"Older Students\", and \"Younger kids\". The school makes different routes on a map and ass
It sounds like the relationships between these objects could be summarized as:
As we know, the Firebase Realtime Database is a NoSQL database and therefore doesn't explicitly support relationships, but they can be inferred in the structure, so take this structure for example (where ...
is your existing values):
schoolId
users
userId
...
markers
markerId
...
route // the route ID that this marker belongs to
routes
routeId
...
markers // list of marker IDs that belong to this route
Note: To keep this example simple, I'll ignore the
users
relationships for now and just work with the relationships betweenmarkers
androutes
.
With this structure: whether we are currently working with a marker or a route, we can easily find out how they relate to each other.
It is then easy to get all markers related to a specific route by performing a query against the route
value of children in the markers node:
schoolReference.child("markers").orderByChild("route").equalTo(routeId);
Where routeId
is the unique ID of the route we are currently working with.
You'll need to be aware of some changes when creating objects though, so for example, when you create a marker with this structure, you'll need to:
route
value of the marker to the the ID of the route that it belongs to, andmarkers
list under the route that it belongs to.You can achieve this in one write operation using a transaction or a multi-location update.
Note: You don't actually have to use the
routeId/markers
list, but it can be useful if you're using FirebaseUI to display indexed data.
This technique of using IDs as index keys is called data fan out and you can read more about it in the structure your database documentation.