Retrieving subcollection data in Firestore using Angular

I am facing the challenge of extracting data from a subcollection within my database structure. Within my main collection products, there are documents that have a nested subcollection called reviews.

products/prodID/reviews/reviewID

Here is my interface setup:

interface IReview {
  author: string;
  text: string;
  rating: number;
}

export interface IProduct {
  id: string;
  name: string;
  reviews: IReview[]
}

Function used to fetch data from the database

getProductsFromDB(): Observable<IProduct[]>{
  return this.db.collection('products').snapshotChanges()
    .pipe(
      map(actions => {
        return actions.map(a => {
          let data = a.payload.doc.data() as IProduct;
          data.id = a.payload.doc.id;
          return data;
        });
      })
    );
}

The issue I'm encountering is that the current function only retrieves data from the main products collection, whereas I actually require the subcollection data to be included in the output as well.

Answer №1

To access a subcollection in Firestore, you need to specify the subcollection path. Here is an example code snippet:

fetchProductsFromDatabase():Observable<IProduct[]>{
  return this.firestore.collection('products/{productId}/reviews').snapshotChanges()
    .pipe(
      map(actions => {
        return actions.map(action => {
          let productData = action.payload.doc.data() as IProduct;
          productData.id = action.payload.doc.id;
          return productData;
        });
      })
    );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble showing Firestore timestamp as a date in an Angular template using toDate()

I'm working on a code snippet that retrieves data from the Accounts collection: db.collection("Accounts").get().then((querySnapshot) => { if (!querySnapshot.empty) { $scope.accounts = querySnapshot.docs.map(doc => doc.da ...

What steps should I take to ensure that TypeScript acknowledges the validity of my object assignment?

Trying to implement this code: type A = { b: false, } | { b: true, p: string; } function createA(b: boolean, p: string | undefined): A { if (b && p === undefined) { throw 'Error'; } const a: A = { b, ...

Here is an example showcasing how to use Angular 2 to make an

How can I correctly retrieve json data from an http get request in Angular 2? Currently, I am working on testing some local data with a mocked endpoint. Although I am able to see the result in the http.get() method, I am facing issues when trying to assign ...

Parsing difficulties encountered: the element 'ion-col' is unrecognized

As I strive to develop Ionic 4 applications, a new error continues to surface even after attempts to resolve the previous one. Following the creation of a custom component mentioned in this error (How to load other page inside of an ionic segment?), a new ...

Tips for running a Nativescript-Angular app in the background

I am currently developing a hybrid app using NativeScript and Angular that has the capability to send real-time location updates from the user to a server via the geolocation plugin, among other features. While everything seems to be working fine when the ...

Using TypeScript to transform a tuple type into an object

When dealing with a tuple type like: [session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string] there is a need to convert it ...

Encountered an issue when attempting to post to an ASP.NET Core Web API utilizing Windows authentication

The setup consists of an AspNetCore WebApi using default configuration for Windows authentication and CORS enabled. The client side utilizes Angular with both GET and POST methods implemented. Successfully executing the GET call: this.http.get("https://l ...

Getting a compilation of events attached to a component within Angular

Trying to identify the events being listened to in a component. In this example, event handlers for customEvent1 and customEvent2 are assigned, while customEvent3 remains unused. Is there a way to retrieve this list, particularly within AfterViewInit? & ...

Issue with Moment Js: Unable to change date with time zone function

Trying to convert a UTC date and time to local time ("Europe/Paris") using moment's timezone function, but encountering issues. The code I am using is: var m = moment.tz(this.startTime, 'Europe/Paris'); this.startTime = m.format("YYYY-MM-DD ...

Utilize swipe gestures in tables with Angular and Ionic for enhanced user interaction

I'm working on creating a swiping functionality for table pagination. Swiping right will take you to the next page, while swiping left will move you back to the previous page. Here's the code snippet of my table: <table #tableElement id=&qu ...

Encountering the NullInjectorError: No provider for Injector! error repeatedly while attempting to interact with a store

I've been working on a web app that incorporates a store by following this tutorial: . However, I keep encountering the following error: main.ts:13 NullInjectorError: StaticInjectorError(AppModule)[InjectionToken @ngrx/store Initial Reducers -> In ...

Unable to load the PDF file in Angular 8 due to an error

I've been attempting to display a PDF in a new browser tab using Angular 8. The PDF is retrieved from a Spring Boot API as a byte array: @GetMapping(value = "/pdf") public ResponseEntity<byte[]> beve(HttpServletRequest request) { return new ...

Endpoint not returning data as expected

I'm facing an issue with my routing module where I have successfully used activatedRoute for multiple other modules but now running into trouble when implementing it in a new singular component. The structure of my routing module is as follows: const ...

Utilize a ReplaySubject to capture and replay only the most recent value from an observable stream

Here is my ReplaySubject setup: matchCount = new ReplaySubject<number>(); totalCount = new ReplaySubject<number>(); This is how I am utilizing it: getMatchedEventsCount(){ return this.dcs.matchCount.asObservable(); } getTotalEvent ...

Utilizing TypeScript for messaging in React Native and React

I have encountered a specific issue with my React projects. When using npx without Typescript, I receive error messages as shown in the following screenshots: https://i.sstatic.net/g68ho.png https://i.sstatic.net/Kmye5.png Interestingly, in my React Nat ...

Troubleshooting Issue with Accessing ASP.NET Core WebApi through Ionic

Having trouble making a connection between my ASP.NET Core WebAPI and Ionic application. The data seems to be loading correctly based on the developer tools, but an error is thrown by Ionic: Error message from Ionic: https://i.sstatic.net/CXroV.png Here ...

How to Merge Items within an Array of Objects Using Typescript?

I'm currently facing a challenge in combining objects from an array of Objects in typescript. The structure of the array is as follows: 0: {type: 'FeatureCollection', features: Array(134)} 1: {type: 'FeatureCollection', features: ...

After the condition in Angular 9 has been altered, the hidden directive fails to display previously hidden elements

I am dealing with two distinct components. First is the app component: This particular component includes an Angular Material button toggle and some sample data. Second is the results component: This component's main purpose is to display the data ...

Collada integration with Angular using Three.js

Requesting assistance to develop a webapp using Angular4 with THREEjs for viewing Collada Objects, but encountering challenges. UPDATE: Seeking a working example or helpful hints as efforts in researching and exploring code with other loaders have prove ...

Steps for confirming whether each element in the array includes the specified search string using Typescript and protractor

How can I verify if each element in an array contains a specific search string in Typescript/Protractor? The issue I faced was that the console statements were returning false because they searched for exact matches instead of the search string. Any sugg ...