Having difficulty accessing precise user information (Nestjs, TypeORM)

Encountering an issue with retrieving specific user data. When saving, a user object and an array of IDs are obtained. The database saving process is successful; however, upon retrieval, not all columns (specifically userId and assetId) are included in the output. Instead of fetching data for a particular user, it returns data for all users. Any suggestions on how to correctly implement the request so that only the user's data (including all columns) is returned?https://i.sstatic.net/HVCep.png

------ controller.ts ------------------

@Controller()
export class UserAssetsController {
  constructor(private readonly assetsUsersService: UserAssetsService) {}

  @UseGuards(JwtAuthGuard)
  @Post()
  async saveUserAssetsData(@Body() dto: UserAssetCreateDto, @Request() request: any) {
    const user = request.user
    return this.assetsUsersService.saveUserAssets(user, dto)
  }

  @UseGuards(JwtAuthGuard)
  @Get()
  async getUserAssetsData(@Request() request: any) {
    return this.assetsUsersService.getUserAssets(request.user)
  }
}

-------- service.ts ----------------------

@Injectable()
export class UserAssetsService {
  constructor(
    @InjectRepository(UserAsset) private readonly repository: BaseRepository<UserAsset>,
    @InjectRepository(Asset) private readonly assetRepository: BaseRepository<Asset>,
    private readonly cache: CacheService
  ) {}
  async saveUserAssets(user, { assetIds, orderOnPage }: UserAssetCreateDto) {
    const userAssets: Array<UserAsset> = []
    for (let i = 0; i < assetIds.length; i++) {
      const assets = await this.assetRepository.find({ where: [{ id: assetIds[i] }] })
      for (const assetIndex in assets) {
        const userAsset = this.repository.create({
          user,
          orderOnPage,
        })
        userAsset.asset = assets[assetIndex]
        await this.repository.save(userAsset)
        userAssets.push(userAsset)
      }
    }
    console.log(userAssets)
    return userAssets
  }

  async getUserAssets(user) {
    return this.repository.find()
  }
}

---------- model.ts -----------------------------

@Entity('user_assets')
export class UserAsset extends TimestampMixin {
  @ManyToOne(type => User, user => user.assets, { onDelete: 'CASCADE' })
  user: User

  @ManyToOne(type => Asset, { onDelete: 'CASCADE' })
  asset: Asset

  @Column({ nullable: true, length: 250 })
  offlineAssetCustomName: string

  @Column({ nullable: true })
  offlineAssetAnnualRate: number

  @Column()
  orderOnPage: number

  @OneToMany(type => UserAssetComment, comment => comment.asset)
  comments: UserAssetComment[]

  @OneToMany(type => UserAssetAlert, userAssetAlert => userAssetAlert.asset)
  alerts: UserAssetAlert[]
}

Answer №1

If you are working with Typeorm, it will only return properties that have been defined using a Column decorator. To ensure that your reference columns are returned, you simply need to add them as columns in your Entity. Here is an example:

@Entity('user_assets')
export class UserAsset extends TimestampMixin {
  @ManyToOne(type => User, user => user.assets, { onDelete: 'CASCADE' })
  user: User
  
  // User reference column
  @Column()
  userId: number

  @ManyToOne(type => Asset, { onDelete: 'CASCADE' })
  asset: Asset

  // Asset reference column
  @Column()
  assetId: number

  //rest of your entity
}

Once you have set up the reference columns in this way, you can use them as options in a find operation. Your function could look something like this:

async getUserAssets(user) {
    return this.repository.find({userId: user.id})
}

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

Why am I receiving the error message "Argument of type 'number' is not assignable to parameter of type 'never'?"

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { showSecret = false; logArr ...

When using Vue 3 in my app, I discovered that all the TypeScript files are easily accessible through the browser console

I recently completed my Vue3 js app with Typescript, and I have noticed that all the Typescript files are easily accessible for anyone to view through the Sources tab of the browser console. The code is perfectly clear and readable. Is there a method to p ...

Utilizing a LoopBack4 Interceptor to access repositories within the application

I am looking to improve the functionality of an Interceptor within my LoopBack4 application. Currently, the Interceptor simply displays the start and end of a controller method call on the command line, as outlined in this documentation. Here is how my Lo ...

Navigating within components using code is an essential skill when working with Vue Router

I am currently developing a Quasar application powered by Vue 3 with vue-router version 4 All my routes are properly configured and function well when navigating from a component template using <router-link to="/route">Go to route</rout ...

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

Discover the secret to creating an efficient TypeScript function that offers autocomplete with enum values

I'm attempting to achieve a scenario similar to the code below: enum Color { RED="RED", GREEN="GREEN", BLUE="BLUE" } function setColor(color:Color) { } However, when I attempt to call the function like this: setColor("RED"), I encounter the ...

Tips for converting necessary constructor choices into discretionary ones after they have been designated by the MyClass.defaults(options) method

If I create a class called Base with a constructor that needs one object argument containing at least a version key, the Base class should also include a static method called .defaults() which can set defaults for any options on the new constructor it retu ...

Uncertainty arises when trying to understand the callback function supplied to the `addEventListener` method in JavaScript

Question: I was recently exploring JavaScript's native addEventListener function. Typically, we use it like this: js selectElement.addEventListener('change', (event) => { const value = event.target.value }); However, when studying the ty ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Navigating with Angular: Every time I refresh the page or enter a specific URL, Angular automatically redirects to the parent route

In my CRM module, I have created a custom Routing Module like this: const routes: Routes = [ { path: 'crm', component: CrmComponent, children: [ { path: '', redirectTo: 'companies', pathMatch: 'full&ap ...

Setting style based on the condition of the router URL

I am currently facing an issue with a global script in Angular 10 that is supposed to evaluate the current path and apply a style to the navigation bar conditionally. However, it seems to fail at times when using router links. I am wondering if there is a ...

Node appears to be struggling to find the cors

I added the cors package and confirmed that it's inside the node_modules directory. However, I keep encountering this error message. /usr/src/app/node_modules/ts-node/src/index.ts:859 server | return new TSError(diagnosticText, diagnosticCodes, ...

What is the best way to bring a local package into another npm package and verify its functionality using Typescript?

In a scenario where there are 3 npm projects utilizing Webpack and Typescript, the folder structure looks like this: ├── project1/ │ ├── tsconfig.json │ ├── package.json │ ├── src/ │ │ └── index.ts │ ...

"Trouble arises when trying to import a Vue component into a TypeScript file

Within my Vue project, I have created a new TypeScript file named Validation.ts: import Vue from 'vue'; import BaseInput from '@/components/base/BaseInput.vue'; class ValidationService extends Vue { validateFields(fields: BaseInput[] ...

Issue with running gulp ser on first attempt in SPFX

Every time I try running gulp serve, I encounter the following issue: Error: Unable to locate module '@rushstack/module-minifier-plugin' Please assist me with this problem. Thank you! ...

Preventing nested prototype methods from being transferred between objects in a WebWorker

My challenge is to reserialize an object from a WebWorker while maintaining the same definitions. However, upon receiving the message, all of the prototype functions are lost. The current solution I have only works for first level prototype functions, bu ...

Is there a way to enable intellisense in vscode while editing custom CSS within a material-ui component?

Is there a vscode extension recommendation for intellisense to suggest css-in-js for customized material ui components in .tsx files? For example, I want intellisense to suggest 'backgroundColor' when typing. The closest I found is the 'CSS- ...

Encountering Canvas errors while utilizing TypeScript in the most recent version of VS Code

Currently, I'm working on TypeScript Canvas code for my application and encountering an error message that says: The type 'CanvasRenderingContext2D' does not have the property 'wrapText'.ts(2339) This error is triggered by this li ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...