Struggling to retrieve all the properties of an Entity in TypeORM and NestJS

I've been working on building a server using typeORM and NestJS. I have set up a one-to-one relationship between my User and Shop classes, with the foreign key shopId in the User table. However, when trying to retrieve a user, the associated shop is not being fetched. What should I do? Here's my User class:

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;
  @Column('text')
  name: string;
  @Column('text')
  email: string;
  @Column('text')
  phoneNumber: string;
  @Column('text')
  password: string;
  @Column('boolean')
  isAdmin: boolean;

  @OneToOne(() => Shop, (shop) => shop.user)
  @JoinColumn()
  shop: Shop;

  constructor(
    name: string,
    email: string,
    phoneNumber: string,
    password: string,
  ) {
    this.name = name;
    this.email = email;
    this.phoneNumber = phoneNumber;
    this.password = password;
  }
}

And here's my Shop class:

export class Shop {
  @PrimaryGeneratedColumn()
  id: number;
  @Column()
  name: string;

  @OneToOne(() => User, (user) => user.shop) // specify inverse side as a second parameter
  user: User;
  @OneToMany(() => Order, (order) => order.shop)
  orders: Order[];
  @OneToMany(() => Product, (product) => product.shop)
  products: Product[];

  constructor(name: string) {
    this.name = name;
  }

The function in UserService that fetches the desired User is as follows:

export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private dataSource: DataSource,
  ) {}
  
  findOneByPhoneNumber(phoneNumber: string): Promise<User> {
    return this.userRepository.findOneBy({ phoneNumber });
  }
  ...
}

However, when the function returns a user, the associated shop is missing from the response, with only the other user fields being returned.

This is the current response:

{
  name: 'test',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d19081e192d0a000c0401430e0200">[email protected]</a>',
  phoneNumber:'+251912345678',
  password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
  id: 1,
  isAdmin: false
}

I was expecting the related shop object to be included in the response. What am I missing or doing wrong here?

Answer №1

There was a need to modify the function within the UserService class to

findOneByPhoneNumber(phoneNumber: string): Promise<User> {
    return this.userRepository.findOne({
      relations: { shop: true },
      where: { phoneNumber },
    });
  }

After making the necessary changes, the outcome was as indicated below

{
  name: 'Ameen Zuber',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e988848c8c87c7869c848c9ba98e84888085c78a8684">[email protected]</a>',
  phoneNumber: '+251939881843',
  password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
  id: 1,
  isAdmin: false,
  shop: Shop { name: 'Box', id: 1 }
}

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

Angular button for opening or closing the menu that redirects the page to a localhost URL

I have implemented a template from the link below into my project. So far, everything has been working fine, but recently I noticed that the menu open/close button is malfunctioning. Whenever I click on the close button while on any page (for example, http ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

Guide to defining a typescript class property using an index signature

type TField = { field1: string; field2: boolean; field3: TMyCustom; } class Test1 { // I opt for using TypeScript's index signature to declare class fields [key: keyof TField]: TField[typeof key] // Instead of individually declaring each ...

Using an object hierarchy in Typescript to create an if statement

Currently, I am attempting to create a logical statement using a hierarchy structure as shown below: if ((config.elementConfig.curve[0].dataset[0].splitBy = 'my discrete var')) {..... However, when implementing this statement, I encounter the er ...

Utilizing TypeScript with Vue3 to Pass a Pinia Store as a Prop

My current stack includes Typescript, Pinia, and Vue3. I have a MenuButton component that I want to be able to pass a Pinia store for managing the menu open state and related actions. There are multiple menus in the application, each using the same store f ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

React TypeScript error: Cannot access property "x" on object of type 'A | B'

Just starting out with react typescript and I've encountered the following typescript error when creating components: interface APIResponseA { a:string[]; b:number; c: string | null; // <- } interface APIResponseB { a:string[] | null; b:number; d: ...

Steps to create a TypeScript function that mimics a JavaScript function

As I look at this javascript code: // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...

The element 'x' is not found within the 'unknown' type

I've been struggling with this issue. After searching through various sources like stackoverflow and github, I attempted a solution which involved adding a generic but I encountered the error message Expected 0 type arguments, but got 1. in relation t ...

Using Highcharts to dynamically color a map based on data values in a React TypeScript project

I'm attempting to generate a map where each country is filled with colors based on its specific data, similar to the example shown in this map. I am looking for a functionality akin to the use of the formatter function within the tooltip. I have expe ...

Executing a single insert statement in a TypeScript Express application using PostgreSQL is taking over 240 milliseconds to complete

Seeking assistance with optimizing a db insert operation test using mocha for a node.js express app that utilizes fp-ts and pg npm package. The tests run successfully, but the insert test is taking over 240 ms to complete. The database table has a maximum ...

Unable to retrieve the key value from a child object in Angular 2 when working with JSON Data

Currently, I am using Angular and attempting to extract data from the child object's key value. Here is the JSON data provided: "other_lessons": [ { "id": 290, "name": "Christmas Test #290", "course": { "id": ...

Ways to receive one of two variations

Dealing with different cases for type is my current challenge. In a React Functional Component, I have a callback function property that accepts an argument of either string or number. interface InputProps { getValue?: (value: string | number) => vo ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

In the Angular Google Maps API, is it possible to update the attributes of <agm-marker> directly within the TypeScript code?

Currently, I am fetching markers from the database and displaying them on a map using Angular Google Maps (AGM) by utilizing the <agm-marker> tag. In my code snippet below, you can see how I fetch and store the markers in an array named markers in t ...

Unable to access due to CORS restriction on Express server

Whenever I attempt to send a POST api request to my express server, I encounter the following error message. Access to XMLHttpRequest at 'localhost:8081/application' from origin 'localhost:8083' has been blocked by CORS policy: No &apos ...

How do you manage dependencies for nested components within Angular2?

Encountering an Issue: browser_adapter.js:76 Error: Cannot resolve all parameters for NestedComponent(undefined). Make sure they all have valid type or annotations. at NoAnnotationError.BaseException [as constructor] Diving Deeper Into the Problem: ...

There seems to be an issue with the OpenAPI generator for Angular as it is not generating the multipart form data endpoint correctly. By default

Here is the endpoint that needs to be addressed: @PostMapping(value = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public List<FileReference> handleFileUpload( @RequestPart(value = "file", name = "f ...

Exploring Typescript's type narrowing capabilities through destructuring

This code snippet is encountering errors: type Example = { x: true, y: null, z: null } | { x: false, y: Error, z: null } | { x: false, y: null, z: { val: number} } function getExample(): Example { return { x: false, y: null, z: { val ...