Filter on document reference as a field

Viewed 238

I have 3 collections:

  1. User => with some field
  2. Organization => with some field
  3. UserOrg with fields like:
    • uid // user id
    • orgid // orgid
    • userDetails // document reference of user doc like user/uid
    • orgDetails // document reference of org doc like org/uid

Now I need to fetch user details of user details

My code is:

return this.dbCollectionService.userOrganizationCollection.snapshotChanges()
      .pipe(map(res => {
        return res.map(data => {
          var userData = data.payload.doc.data()
         let userDetails : any;
         if (userData.userDetails) {

this.angularFirestore.doc(userData.userDetails).valueChanges().subscribe(res => {
          userDetails = res;
          console.log(userDetails);
        });

      return { id, ...userDetails }

    }).filter( f => f.organizationId != undefined && f.organizationId == orgId)
  }));

This is able to console the result correctly, but not returning data.

Could be getting data from data reference taking time and return statement executes earlier.

1 Answers

The return { id, ...userDetails } is executed before the subscription on the this.angularFirestore .doc(userData.userDetails).valueChanges().

Subscription inside a subscription is not a good idea, you should use other pipable operators like switchMap to chain the two calls :

return this.dbCollectionService
.userOrganizationCollection.snapshotChanges()
.pipe(
   map(res => res.map(data => data.payload.doc.data())),
   map(userDatas => userDatas.filter(_ => _)),
   map(userDatas => userDatas.map(this.angularFirestore.doc(userData.userDetails).valueChanges()
                                    .pipe(map(userDetails => ({ id, ...userDetails }))))),
   switchMap(userDatas$ => combineLatest(userDatas$)),
   map(users => users.filter( f => f.organizationId != undefined && f.organizationId == orgId))
);
Related