Retrieving Subcollection Data within a Firebase Document

I have an angular 8 typescript interface set up that contains an array of another interface as a variable. Here is the structure:

export interface User {
    name: string;
    id: string;
    history: Job[];  //this part isn't getting populated
}

The Job interface is defined as follows:

export interface JobJson {
    id: string;
    price: number,
    notes: string
}

My database setup involves using Firebase's Cloud Firestore and has the following structure:

users // collection

|--> user1234 // document

|--> jobs //subcollection

|--> job1234 // sub document

When I retrieve a user from firebase using a query:

this.firestore.collection<UserJson>('users').doc<UserJson>(id).valueChanges().subscribe((u) => {
    // work with u data here
  });

As anticipated, the history field in user object remains empty. However, it is essential for my program to populate the user.history array with the subcollection data under user in Firebase. Is there a way to achieve this? Any assistance would be appreciated!

Answer №1

It seems that there is no direct way to retrieve this information in a single call to Firestore. A workaround involves making two calls if you know the collection name, or three calls if you're unsure about the collection name.

Referencing the documentation, none of the methods in DocumentReference provide both document snapshot and collection data simultaneously.

In my case, I've included code snippets that simply log the content to the console for demonstration purposes.

Without knowing the subcollection's name: This snippet fetches all subcollections along with their elements:

db.collection('users').doc(str[6]).get().then(documentSnapshot => {
  console.log(documentSnapshot.data());
});

db.collection(COLLECTION_ID).doc(DOCUMENT_ID).listCollections().then(collections => {
  for (let collection of collections) {
    console.log(`Found subcollection with id: ${collection.id}`);
    collection.get().then((snapshot) => {
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });
  }
});

Knowing the specific subcollection:

db.collection(COLLECTION_ID).doc(DOCUMENT_ID).get().then(documentSnapshot => {
  console.log(documentSnapshot.data());
});

db.collection(COLLECTION_ID).doc(DOCUMENT_ID).collection(SUBCOLLECTION_ID).get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
      console.log(doc.id, '=>', JSON.stringify(doc));
    });
  })

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

Tips for leveraging constant values in TypeScript 'Type Aliases' for improved code organization

I am a beginner in the world of TypeScript. Currently, I am working on an Angular Project where I am developing a SnackBar Service to provide notifications to users. Although my background is primarily in Java, I have encountered some challenges. I have ...

Ahead of Time compiled Angular applications utilize computed object/map/dictionary keys for optimal performance

In my Angular project, we are exploring the idea of defining routes as Enums and then declaring the specific routes that they should point to. These Enums are linked to string values that correspond to keys in our CMS-system. Initially, we tried a simple ...

In Electron, methods for detecting and resolving Error TS2304: Unable to locate the name 'unknown on(event: 'ready', listener: (launchInfo: unknown) => void): this are essential for smooth operation

Encountering an issue while running npm build. Electron version: 7.1.2 TypeScript version: ^2.5.1 Target version: ES2017 Here are the details of the error. When I performed the build under the following conditions: Electron version: 6.0.0 TypeScript ver ...

I don't use Angular to execute a function when (load) is triggered

Whenever I try to open the div, the function doesn't seem to work correctly. Sample HTML: <div class="row table-dark table-bordered"> <div class="col-xl-12" (click)="isCollapsed=!isCollapsed;"> Click Me! <ng-container *ngIf= ...

Xamarin.Android Firebase authentication causing system crashes

Currently utilizing Firebase authentication version 42.1021.1 (latest stable). Within the OnCreate method, my code looks like this: var firebaseApp = FirebaseApp.InitializeApp(this); var authIntance = FirebaseAuth.GetInstance(firebaseApp); However, I am ...

Exploring nested JSON responses in Angular 2 with TypeScript

Below is the JSON response I received from the REST endpoint: {"image_2_11_0-51-upgrade.iso": {"model": "somemodel", "hostnames": ["abc.com", "abcd,com"], "upload_status": false, "version": "2.11.0-51"}, "image_2_11_0-51-upgrade.iso": {"model": "newmo ...

Unlinked from the main content, the Angular2 Material2 sidenav stands on its

I am in the process of implementing the material2 sidenav component. My goal is to have a standalone, full-height sidebar that smoothly slides in and out without any interference with the rest of the app layout caused by the sidenav-layout. The desired ou ...

Angular 9: Issues with [innerHTML] not displaying unclean values, even for simple strings

I am facing an issue with two angular 9 apps in monospace font. In one of the apps, the code snippet below does not display any text on the browser document: Component: myText = "some text" Template: <p [innerHtml]="myText"><p> Even if I ...

Firebase hosting encounters issues when trying to access node api routes

I am facing an issue with my route '/' as it serves the public HTML index file instead of routing to the desired location. I attempted to change the root directory of my API to /api/**, but encountered a 404 error. The application runs smoothly w ...

Discover the process of enhancing features in an Angular component with JavaScript functionality

I am currently working on a shopping cart project and I need to implement the functionality to add products to the cart. Can Angular scripts be used in the way shown in my code snippet, or is there another solution that may work better? <div> < ...

Angular: Exploring the most effective strategies for optimizing code within the ".subscribe()" method

Imagine having a component structured like this The Initial Code: import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<pre>{{ ...

What methods does Angular use to determine the parameter types of a constructor?

I've been experimenting with replicating Angular's approach to interpreting the constructor in an injectable service. function Injectable() { return function<T extends { new (...args: any[]): {} }>(con: T) { return class extends con ...

Struggling with deploying to Firebase hosting

When I run firebase deploy, it runs for a few minutes before giving me a timeout error Error: ESOCKETTIMEDOUT I have successfully deployed multiple times before, without making any changes other than the frontend of my React project. My cloud functions i ...

What could be the reason for the validation failure?

companyprofile.html <form #f="ngForm" name="companyProfileForm" ng-submit="companyFrmSave(objCS, objCSCurrency)" novalidate=""> <div class="row form-group"> <div class="col-md-12" > ...

Determined the type of props conditionally based on the value of the

I need to create a TextField component that dynamically switches between using input or textarea based on the value of the multiline property. I'm having trouble figuring out how to conditionally set the type of my element based on the multiline valu ...

Personalized hue for angular2-material's md-progress-circle component

Is it possible to customize the color of my md-progress-circle element to something other than the default? <md-progress-circle mode="determinate"></md-progress-circle> I'm facing an issue where I cannot find a specific class to over ...

The ordering of my styles and Material-UI styles is causing conflicts and overrides

Greetings fellow developers! I'm currently facing an issue with my custom styles created using makeStyles(...). The problem arises when I import my styles constant from another module, and the order of the style block is causing my styles to be overr ...

Unable to delete event count within angular-calendar

Currently, I am utilizing the angular calendar library from here. My goal is to eliminate the total event counts displayed on the calendar. View Image I have implemented encapsulation as ViewEncapsulation.None in my component file, and here is how my C ...

Having trouble with the dropdown button functionality when looping through it in Angular

Currently, I am working with Angular and have implemented a tree-based structure. Within this tree structure, there is a dropdown button labeled "Dropdown." The issue at hand is that when I click on the "Dropdown" button, the dropdown functionality does ...

Utilizing AMD Modules and TypeScript to Load Bootstrap

I am attempting to incorporate Bootstrap into my project using RequireJS alongside typescript AMD modules. Currently, my requireJS configuration looks like this: require.config({ shim: { bootstrap: { deps: ["jquery"] } }, paths: { ...