'How to get realtime updates of sub-collection data of a collection

I am using Angular and Firestore Database building a job site like 'LinkedIn'.

I have created a collection called users which have few data such as name, age and etc. Also this collection have a sub-collection called work-experience. This work-experience sub-collection maybe have multiple document with unique document id.

The issue I am facing is that when I am changing anything that is the main collection means users. I am getting realtime changes for name and etc.

But let's just say I have just created a new work experience. I successfully stored it in the database but I am not getting the data in Realtime in UI.

Here is my code snippet.

get currentUserProfile$(): Observable<any> {
  return this.authService.currentUser$.pipe(
    switchMap((user) => {
    if (!user?.uid) {
      return of(null);
    }

    const user$ = docData(doc(this.firestore, 'users', user?.uid));
    const workExperience$ = this.getWorkExperiences(user.uid);

    return combineLatest([user$, workExperience$]);
  })
 );
}


getWorkExperiences(uId: string) {
   return from(getDocs(collection(this.firestore, `users/${uId}/work-experience`)))
}

What needs to be done to get real time updates of my work-experience sub-collection data?



Solution 1:[1]

All read and listen operations on Firestore are shallow, and only read documents from the collection (or group of collections with the same name) tht you attach the observer too.

This means you will need to attach a second listener for each user that you want to listen to the skills of, or alternatively use a collection group query to listen to all skills subcollections in one go.

Alternatively, you can add some metadata to the user's parent document about the skills. For example, you could replicate the minimal information about the skills that you need to display in the list of users, so that you don't need to read/monitor all the skills subcollections. You could even just keep a skillsLastUpdated field in the parent document that you update whenever you write the skills for that user. With this your parent document will be updated when its children are changed, so you can trigger off that.

If this sort of data duplication is new to you, I recommend checking out NoSQL data modeling and watching Getting to know Cloud Firestore.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen