Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularFire - combine two FireStore collections with the same pushId items

I'm working on some project with AngularFire + FireStore.

My Firestore model looks like this:

  • Collection 1

    • key1 {some data}
    • key2 {some data}
  • Collection 2

    • key1 {other data}
    • key2 {other data}

Now I need to show list where I have some data from the first collection, and some data from another one. How to create such a list?

It seems to be pointless to make two observables and then merge it.

const collection = this.afStore.collection<any>(collectionName);
    return collection.snapshotChanges()
      .map(participants => {
        return participants.map(participant => {
          const data = participant.payload.doc.data();
          const id = participant.payload.doc.id;
          return {id, ...data};
        });
      });
      

I have this code that takes data + id, and now I need to use this id to pull data from another collection, but don't know how.

like image 338
Stasiek Sarnecki Avatar asked May 23 '26 21:05

Stasiek Sarnecki


1 Answers

Here's how I did mine...

The "projects" data has customer_doc_id, customer_builder_doc_id, customer_contractor_doc_id, which are doc_id of other data collections in Firestore. The command mergeMap works in rxjs^5.5.0.

 private getProjectsCombineObservables(): Observable<any[]> {
this.projectsCollection = this.afs.collection<Project>('projects', ref =>
  ref.orderBy('job_number', 'desc'));
return this.projectsCollection.snapshotChanges()
  .map(actions => {
    return actions.map(a => {
      const project_data = a.payload.doc.data() as Project;
      const doc_id = a.payload.doc.id;

      let observable1 = this.getCustomer(project_data.customer_doc_id);
      let observable2 = this.getBuilder(project_data.customer_builder_doc_id);
      let observable3 = this.getContractor(project_data.customer_contractor_doc_id);

      const combinedData = Observable.combineLatest(observable1, observable2, observable3, (data1, data2, data3) => {
        return { ...data1, ...data2, ...data3 };
      });

      return combinedData.map(data => Object.assign({}, { doc_id, ...project_data, ...data }));
    });
  }).mergeMap(observables => Observable.combineLatest(observables));

}

like image 72
Joe Avatar answered May 26 '26 19:05

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!