How To Join Firebase Firestore Collection Documents(Tables) By Id.

Lets look on how we can do a join in `firestore`. We will be using `RxJs switchMap` operator. Lets say you have a table of users, each user is identified by their `userid(uid)`. You have another collection document(table) of users blog post`(post)`. Each post stores the author `uid(uid)`.

1
2
3
4
5
firebase documents
Users' Table| uid | photoURL | displayName |            
| jackass | avatar.png | James Bond 

Blogs' Table| id | title | uid | 

This is a blog post title | jackass | As you can see from the tables, our unique identify is the `uid` field whose value in both tables is `jackass` Now we want to fetch all post and join each post with the associated author details. We will create a service call `blog.service.ts`

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
//javascript
blog.service.ts
file getPages(){ const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));     
 return item.valueChanges().pipe(switchMap(arr => {      
  const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`)    .valueChanges().pipe(first()) );      
  return combineLatest(...userObservable) .pipe( map((...users) => {      
  arr.forEach((author, index) => {
    author['author_avatar'] = users[0][index]['photoURL'];                  
    author['author_username'] = users[0][index]['displayName'];      
  });              
  return arr;    
  })    
 );  
 }));      
} 

Make sure you import all the necessary RxJs libraries.

You can join other documents(tables) to the given query above by just adding another `switchMap` operator.

That's it! Have any questions, leave a comment below.

Related Posts

0 Comments

12345

    00