What is the process of transforming a Firebase Query Snapshot into a new object?

Within this method, I am accessing a document from a Firebase collection.

I have successfully identified the necessary values to be returned when getUserByUserId() is invoked, but now I require these values to be structured within a User object:

getUserByUserId(userId: string) {
    return of(firebase.firestore().collection("users").where("userId", "==", userId)
      .get().then(querySnapshot => {
        querySnapshot.forEach(doc => {
          console.log("User ID", "=>", doc.data().userId);
          console.log("Username", "=>", doc.data().userName);
          console.log("Mechanic", "=>", doc.data().isMechanic);
          console.log("Location", "=>", doc.data().location);
        })
      }).catch(err => {
        console.log(err);
      }));
  }

The following outlines the structure required for the User data:

import { PlaceLocation } from './location.model';

export class User {
    constructor(
        public id: string,
        public name: string,
        public isMechanic: boolean,
        public email: string,
        public location: PlaceLocation
    ) { }
}

Could someone guide me on creating a User object with this data and returning it as the response of getUserByUserId()?

Answer №1

Utilizing @angular/fire allows you to perform the following actions:

constructor(private firestore: AngularFirestore) {
}

getUserByUserId(userId: string) {

    return this.firestore
      .collection("users", ref => ref.where("userId", "==", userId))
      .get()
      .pipe(
        filter(ref => !ref.empty),
        map(ref => ref.docs[0].data() as User),
        map(data => new User(data, data.location))
      )

}

Updated information

If you require an object instance, you must have an additional constructor like the one mentioned in this reference about object assign.

export class User {
    constructor(
        public id: string,
        public name: string,
        public contactNumber: number,
        public isMechanic: boolean,
        public email: string,
        public password: string,
        public address: string,
        public imageUrl: string,
        public location: PlaceLocation
    ) { }

    public constructor(
      init?: Partial<User>,
      initLocation?: Partial<PlaceLocation>) {

        Object.assign(this, init);
        if(initLocation) {
          this.location = new PlaceLocation(initLocation);
        }
    }
}

export class PlaceLocation {
    constructor() { }

    public constructor(init?: Partial<PlaceLocation>) {
        Object.assign(this, init);
    }
}

Since you are reading data as an object without type, you can only create a new User object explicitly and assign its properties using data from the object.

getUserByUserId(userId: string) {

    return this.firestore
      .collection("users", ref => ref.where("userId", "==", userId))
      .get()
      .pipe(
        filter(ref => !ref.empty),
        map(ref => ref.docs[0].data() as User),
        map(data => new User(data, data.location))
      )

}

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 extracting data from nested JSON structures

I'm trying to retrieve the username of a user from the Firebase Realtime Database, which is stored in a UsersList. I have attempted various methods as shown in the code snippets below: https://i.stack.imgur.com/GsovS.png However, no matter what I tr ...

Switching themes on Angular's ag-grid while maintaining infinite scrolling capabilities

In my Angular 9 application, I have successfully implemented an Ag-grid with infinite scroll. Now, I am looking to add a theme chooser similar to the one showcased in the demo. Simply changing the CSS class does not update the row heights when switching t ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

What is the best way to populate an Angular variable in Ionic following a subscription?

Currently, I am in the process of retrieving data from a server and displaying it on an Ionic page. I have successfully fetched the data without any issues and verified it in the console. However, how do I proceed once the server returns the data to me? T ...

Error encountered when retrieving data from Express using Angular service within Electron

Currently, I am facing a challenge with my Angular 4 app integrated within Electron and using express.js to fetch data from MongoDB. My dilemma lies in the communication process with express through http requests. Within my angular service, there is a met ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

Display the initial occurrence from the *ngIf statement

Is there a way to display only the first match from the *ngIf? I am currently using an object loop with *ngFor, where I have multiple items with the same Id but different dates. I need to filter and display only the item with the most recent date and avo ...

What steps do I need to take for the function to accurately determine the return type?

class Foo { name: string; constructor({name}: {name: string}) { this.name = name; } } class Bar<T extends Foo> { foo: T; constructor({foo}: {foo: T}) { this.foo = foo; } } class CustomFoo extends Foo { xxx: string; constr ...

Required Field Validation - Ensuring a Field is Mandatory Based on Property Length Exceeding 0

When dealing with a form that includes lists of countries and provinces, there are specific rules to follow: The country field/select must be filled out (required). If a user selects a country that has provinces, an API call will fetch the list of provinc ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

Challenges Experienced by AoT in Live Operations

So in my project, I have various components and services included where necessary. To ensure their accessibility, I made sure to declare all the services as private within the constructor. Here's an example: constructor(private myService: MyService) ...

"Error message: The term 'subscribe' is not recognized in Angular

Recently, I started learning Angular and have been following Angular6 tutorials on YouTube here. I encountered an error while working on the project. My goal is to display a list of employees below the existing lists, and I am currently troubleshooting t ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...

Guide for setting up various validations for formGroup in an Angular 5 project

I am currently working on implementing Angular reactive form validation. My existing structure only includes validation for required fields, but I am looking to add additional validations such as minLength, email, and postcode. One challenge I face is cre ...

Techniques for concealing a button when the "disabled" attribute is set to "true"

The button is currently disabled, however, I intended for it to be hidden from the UI when the disabled condition is met - <button ion-button block class="button-color-blue" [disabled]="true" (click)="closePage()"> Cancel </b ...

Issue with Angular date field not displaying invalid input when form is submitted

I am encountering an issue with my simple form that contains only one date control. Whenever I input an invalid date like 30-Feb-2018, the control becomes invalid and my CSS style triggers a red border to indicate the error. The problem arises when the us ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

Modifying the default FilterSettings in ejs-grid: A step-by-step guide

Brand new to Angular and Material technologies, I recently created a grid following the instructions provided here. Below is the html template for the table: <ejs-grid #grid [dataSource]='data' allowFiltering='true' allowPaging=& ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...