The joinAndSelect function in NestJS is having trouble fetching all the data from the PostgreSQL database

In my database, I have three tables named product, branch, and product_branches.

The product table contains columns: id, name

The branch table contains columns: id, name, lat, lng

And the product_branches table contains columns: productId, branchId

I wrote a query to fetch the data as follows:

const query = this.createQueryBuilder('products')
  .leftJoin('products.productBranches', 'productBranches')
  .leftJoinAndSelect(
    'branch',
    'branches',
    'productBranches.branchId = branches.id',
  );

const products = await query.getMany();

The resulting JSON looks like this:

[
{
    "id": "143f6e35-59ae-4185-bed2-a479ec716489",
    "name": "product name",
},
.....]

However, I expect the result to look like this:

[
{
    "id": "143f6e35-59ae-4185-bed2-a479ec716489",
    "name": "product name",
    "branches": [
       {
           "id": "143f6e35-59ae-4185-bed2-a479ec716489",
           "name": "branch name",
           "lat": "lat",
           "lng": "lng",
       },
       ....
    ]
},
....]

When I print out the query using

console.log('query: ${query.getQuery()}');
and run it in PostgreSQL directly, it returns the correct data.

Below are the entity structures for reference:

@Entity()
export class Product {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @OneToMany((_type) => ProductBranches, (productBranches) => productBranches.product, {
    eager: false,
  })
  productBranches: ProductBranches[];
}

@Entity()
export class Branch {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column()
  lat: string;

  @Column()
  lng: string;

  @OneToMany((_type) => ProductBranches, (productBranches) => productBranches.branch, { eager: false, },)
  productBranches: ProductBranches[];
}

@Entity()
export class ProductBranches {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @ManyToOne((_type) => Product, (product) => product.productBranches, {
    eager: true,
  })
  @Exclude({ toPlainOnly: true })
  product: string;

  @ManyToOne((_type) => Branch, (branch) => branch.productBranches, {
    eager: true,
  })
  @Exclude({ toPlainOnly: true })
  branch: string;
}

Note: I also tried using find method with relations but encountered the same issue.

Thank you

Answer №1

The problem is divided into two opposing viewpoints

  1. @Exclude({ toPlainOnly: true }) used on the branch: string; within the ProductBranches Entity

  2. Instead of using createQueryBuilder, it is recommended to use

    const offers = this.find({
       relations: ['productBranches'],
    });
    

However, the branch will now be nested within the productBranches rather than being a separate JSON object

A special thanks to my friend Mohammad Ali for his assistance

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

Using *ngIf with values from an array in *ngFor in Angular 2: How to make it work?

i just started learning angular 2 and ionic, so I'll keep it brief: <ion-card class="acc-page-card" *ngFor="let account of accounts"> <ion-card-content> <!-- Add card content here! --> <ion-item (click)="GoTo('Ac ...

Differences between Angular components and TypeScript classes in models

In my observation, I have noticed that in several instances, manual models are being created for components to specifically manage the data. Despite this, the component already contains a ts class along with the html and css data. Shouldn't the task ...

The feature of declaration merging does not function properly with the express 4.17.* request type

Looking to enhance the Request type, I decided to create a folder @types/express. Within this folder, I included a file index.d.ts with the following content. namespace Express { interface Request { user: number; } } Upon referencing req.user in V ...

Leverage Angular's interpolation feature to display data in tippy-content

Currently, I am working on an Angular project and successfully implemented tippy.js, which you can find working perfectly at this link: . However, the issue arises when I attempt to populate the tooltips with JSON data using Angular's interpolation. ...

Discover the steps to extend static generic methods in Typescript

My issue lies in compiling Typescript code as the compiler doesn't seem to recognize the inheritance between my classes. Whenever I attempt to compile, an error arises: Property 'create' does not exist on type 'new () => T'. ...

Exploring the benefits of integrating Apache Thrift with TypeScript

After running the apache thrift compiler, I now have generated .js and .d.ts files. How do I incorporate these files into my current Angular2/Typescript project? I attempted to do so with the following lines of code: ///<reference path="./thrift.d.ts"/ ...

Is there a TypeScript equivalent to NSUserDefaults or SharedPreferences?

Just getting started with Angularjs-2.3 TypeScript and I have a specific scenario where I need to save the userId in the app so it can be accessed anywhere within the app. If I were developing for Android or iOS, I would typically use NSUserDefaults and S ...

Serialport node failing to receive data

I currently have an RS422 serial device connected to my Windows PC using a USB to serial cable. The cable incorporates an FTDI chip and I am utilizing the corresponding VCP drivers to communicate with the device through a COM port (COM3). https://i.sstati ...

The data structure '{ recipe: null; }' cannot be matched with type 'IntrinsicAttributes & Recipe'

Currently, I am working on an app that integrates ChatGPT to fetch recipes based on user-input ingredients. After receiving the JSON response from CGPT, I aim to display a Recipe "Card" component. However, I encounter an error titled above when attempting ...

What is the best way to transfer the variant property of the material-ui TextField when using a higher-level React component?

I'm encountering difficulties with typing... Essentially, I have a wrapper React component for the @material-ui TextField but I am struggling with getting the typings correct for the variant property. Here's the main problem. Using @material-ui ...

Managing clicks outside of the render function

I'm brand new to using React and I'm currently exploring how to properly manage an event handler outside of the Return() function within a component. If there's a more efficient or conventional way to do this, I'm definitely open to sug ...

Can you explain the contrast between Angular 2 components and directives?

I have been having difficulty grasping the distinction between these two ideas within the framework. I am quite experienced with directives in AngularJS 1.x, and both components and directives in Angular 2 appear to be closely related to this concept... ...

Obtaining an array from within an object in Angular 2 using Typescript

Upon performing a console.log of the following: console.log(this.categories); The resulting structure is displayed below: https://i.sstatic.net/8Wt65.jpg This structure was generated from the JSON retrieved from the API: [ { "id":"dff0bb3e-889f-43 ...

When a property is removed from a variable in an Angular Component, it can impact another variable

During the iteration of the results property, I am assigning its value to another property called moreResults. After this assignment, I proceed to remove array elements from the testDetails within the moreResults property. However, it seems that the remova ...

Upon attempting to send a POST request with PostgreSQL, the following error is displayed: "Invalid input syntax for type integer: '12 Pro'"

I encountered an error while attempting to send a POST request using PostgreSQL/Sequelize. Can anyone help me identify the issue in this code? async create(req, res, next) { try { let { name, price, brandId, typeId, info } = req.body; c ...

Implementing a PhysicsImpostor feature that flips meshes upside-down

After exporting a mesh from Blender and loading it from a GLB file, I encountered an issue with the PhysicsImpostor causing the entire model to flip upside down. Can anyone help me troubleshoot this problem? export class Player extends BABYLON.AbstractMes ...

What is the best way to determine the specific type of a value that is part of a union type?

Utilizing @azure/msal-react and @azure/msal-browser for implementing authentication in a React project with Typescript. The issue arises when TypeScript identifies event.payload as type EventPayload, but does not allow checking the exact type (e.g. Authen ...

My nestjs project is refusing to launch after a system restart

Recently, I've been encountering a strange issue where after rebooting my system, I am required to completely uninstall npm and nodejs before reinstalling them in order to successfully start my nestjs project. Upon running the npm run start command i ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...