Get joined firebase data into Array
I have 2 objects in my firebaseDB businesses and deals. I join them with the operation below. But in order to do more filtering of business deals, I need the returned value as an array. How can I do that after this join operation?
this.businessWithDeals = af.database.list('/businesses').map(businesses => {
for (let business of businesses) {
business.deals = af.database.list(`/deals`, {
query: {
orderByChild: 'business_key',
equalTo: business.$key
}
});
}
return businesses;
});
Our experience is to "avoid joins" with Firebase and store the data redundantly. We still have to "join" the data, we are adding a new property to the parent. The new property can be an object or an array and client can subscribe to it as usual. We always add two properties a) the target for UI, so that the UI has not to worry about it, e.g. details b) the stream itself, e.g. details$
Example with 1 child (details)
get userRaterGroups$(): Observable<any[]> {
return this.af.database.list(/${this.userRaterGroupsRef}/${this.auth.uid}).map((groups) => {
return groups.map(group => {
group.details = {}; // this is for the UI to have an an empty object before subscribing to details$
group.details$ = this.af.database.object(/${this.groupsRef}/${group.$key});
return group;
});
});
}
Example with 1 (details) and n (userRatings) children
get userGroupRatings$(): Observable<any[]> {
return this.af.database.list(/${this.userRaterGroupsRef}/${this.auth.uid}).map((groups) => {
return groups.map(group => {
group.details = {}; // this is only for the UI to have an an empty object before subscribing to details$
group.details$ = this.af.database.object(/${this.groupsRef}/${group.$key});
group.userRatings = []; // this is only for the UI to have an an empty array before subscribing to userRatings$
group.userRatings$ = this.af.database.list(/${this.userRatingsRef}/${this.auth.uid}/${group.$key});
return group;
});
});
}
Client: this.dataService.userGroupRatings$.subscribe((ratings) => { ratings.map(rating => { rating.details$.subscribe(details => { rating.details = details; }); rating.userRatings$.subscribe(ratings => { rating.userRatings = ratings; }); return rating; });
If the order by criteria is in the new property (the "sub-observable"), we store the data on the parent as well, because ordering on this "sub-observable" is possible, but not straight-forward, because the subscription is handled later.
Hope this helps.
Thanks a lot for your comments, I have chosen .subscribe to get the data into array. As you said it is not a good way to join them when using firebase but it needed to be done that way for now. :)