Search code examples
typescriptnestjstypeorm

Having a problem fetching all the attributes of an Entity in TypeORM and Nest


I am using typeORM and NestJS to build a server I have a one-to-one relationship between a User class and a Shop class and the foreign key shopId in the User table but when i try to fetch the user the shop related to it is not being fetched what should I do? My User class is as follows:

@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;
  }
}

My Shop class is as follows:

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 needed User is:

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

when the function returns a user the shop related to it is not there and only the other fields in the user class are sent.

this is what am getting:

{
  name: 'test',
  email: '[email protected]',
  phoneNumber:'+251912345678',
  password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
  id: 1,
  isAdmin: false
}

but i was expecting the related shop object to be in the response as well, what am i missing or doing wrong here?


Solution

  • had to change the function in the UserService class to

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

    and the result was as follows

    {
      name: 'Ameen Zuber',
      email: '[email protected]',
      phoneNumber: '+251939881843',
      password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
      id: 1,
      isAdmin: false,
      shop: Shop { name: 'Box', id: 1 }
    }