0
votes

I have a firestore which will look like this: Cloud Firestore

So in few word I have some users which can log in to my application and create recipe. And in 'My recipe' page I will have the list of recipes that a user is having. So I have 1 collection 'User' and inside that 1 collection 'Recipes' with multiple recipes.

I have implemented the Firestore Google login and this is working as I get uid. etc... THis is inside auth.service.ts:

auth.service.ts

and I want to create a recipes.service.ts with a methode getRecipes() which will getRecipes under users/$(user.uid)/Recipes

anyone can help here? I dont find any tutorial to display data with subcollection.

1
On Stack Overflow, don't share images of code. You should copy the code into the question itself, and format it so that it's easy to read, copy, and search. Please read: stackoverflow.com/help/how-to-ask - Doug Stevenson

1 Answers

0
votes

Welcome to Stackoverflow!

For you to retrieve data of collections with nested collection, you can easily return one, by using a code similar to this: db.collection('users').doc('<user>').collection('Recipes').get(). Using like this, it will return the document with the subcollection, per user.

However, there is no way of getting the sub-collections together with all the documents at once. But, there is a good workaround available here, that for your case would be something like this:

this.firestoreService.colWithIds$('users').pipe(
 switchMap((users: any[]) => { 
   const us = users.map((r: any) => { 
     return this.firestoreService
       .col$(`users/${r.id}/recipes`)
       .pipe(
         map(recipes => Object.assign(user, {recipes}))
       ); 
     }); 
   return combineLatest(...us); 
 })
).subscribe(users => console.log(users);

While I have not tested this code, I believe it's a good starting point for you, since this code is getting the users values mapped to it’s sub-collection observables. Those Recipes values however are mapped back to the user values, with the sub-collection Recipes data containing as a new property.

Let me know if the information helped you!