rxjs – Many to many relationships with AngularFire – Code Utility

[

I have a conceptual problem.

I’ve defined Many to Many relationship in Firestore. I have 3 collections, A, B and A_B. The A_B collection has documents with IdA_IdB {idA: idA, idB:idB}

What I need is to create and Observable of the documents of B that are related with a
document of A.

I do not know which rxjs operator I need to use or how to. I have tried with switchMap or forEach and MergeMap with no success.

My idea is firstly query the collection A_B using ref.where and pass (idA). Then forEach result query B collection passsing docRef.idB and combine the results in one Observable.

Thanks!

,

Basically, for a specific document A, docA you want to:

  • query A_B collection where IdA = docA.Id (let’s call results “relation”)
  • for each relation, query DocumentB collection where Id = relation.IdB
  • return docA with a relatedBs property (DocumentB[])

To accomplish this with rxjs, you can use switchMap, combineLatest and map.

The AngularFire syntax isn’t fresh in my mind, but something like this pseudo-code should work:

1  public documentA$ = this.afStore.document(id).pipe(
2    switchMap(docA => this.afStore.collection('A_B').where('idA', '=', docA.id).pipe(
3      switchMap(relations => combineLatest(relations.map(r => this.afStore.document(r.idB)),
4      map(relatedBs => ({...docA, relatedBs}))
     ))
   );

Here’s an explanation of the flow:

  1. fetch the DocumentA
  2. switchMap #1 fetches related A_B records
  3. switchMap #2 fetches the collection of related DocumentB documents by using combineLatest to create an observable that emits the collection by mapping each relation to an observable that fetches the corresponding DocumentB
  4. map simply returns the original DocumentA with a relatedBs property appended

]