Search code examples
nestjstypeormrelationmany-to-one

With NestJS and TypeORM, can I get away with passing an ID to a @ManyToOne relation?


I'm using NestJS 10 and typeorm 0.3.17. I hvae this entity ...

@Entity()
export class Card {
    @PrimaryGeneratedColumn('uuid')
    id: string;
  
    @ManyToOne(type => User)
    @JoinColumn({name: 'owner_id', referencedColumnName: 'id'})
    author: User;

    ...
}

and its corersponding DTO ...

export class CreateCardDto {
    author: User,
    category: Occasion;
    title: string;
    frontImg: Buffer;
    frontImgAltText: string;
    backImg: Buffer;
    backImgAltText: string;
}

I have a controller method where I set my user based on what is stored in the request object ...

  @Post()
  async create(@Req() req: Request, @Body() createCardDto: CreateCardDto) {
    const userId = req.user['sub'];
    const user = await this.usersService.findById(userId);
    createCardDto.author = user;
    return this.cardsService.create(createCardDto);
  }

and in turn save the object in the service method ...

  async create(createCardDto: CreateCardDto): Promise<Card> {
    return this.cardRepository.save(createCardDto);
  }

What I wanted to know is in the controller method, I look up the user object using the ID

const user = await this.usersService.findById(userId);

but this seems a little wasteful since I only need to save the ID in my target object, but because of the "@ManyToOne" relationship, I define a "User" object in the entity. Is there a more efficient way to do this to save me making an unnecessary database lookup call?


Solution

  • you just use: createCardDto.author = { id: userId } and save it