Luca Valsecchi
Luca Valsecchi

Reputation: 81

TypeORM-NestJS and relations OneToMany insert null foreign key

I'm trying to create a OneToMany relations with NestJS, Typeorm but when I insert to my database, it always insert it with NULL foreign key userId. I tried in various ways but I really don't know how could I solve it.

@Entity()
export class Account extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true })
  apikey: string;

  @Column({ unique: true })
  apikeysecret: string;

  @Column()
  @CreateDateColumn()
  createdAt: Date;

  @Column()
  @UpdateDateColumn()
  updatedAt: Date;

  @Column()
  exchange: string;

  @ManyToOne(() => User, (user: User) => user.accountsaccounts, {
    onUpdate: 'CASCADE',
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'userid', referencedColumnName: 'id' })
  public useruser: User;
}

and

@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;
    
  @OneToMany(() => Account, (account: Account) => account.useruser, {
    eager: true,
    cascade: true,
  })
  accountsaccounts: Account[];

  @BeforeInsert()
  @BeforeUpdate()
  async hashPassword() {
    this.password = await bcrypt.hash(this.password, 8);
  }

  async validatePassword(password: string): Promise<boolean> {
    return bcrypt.compare(password, this.password);
  }
}

and

async create(createAccountDto: CreateAccountDto, user: User) {
    const { apikey, apikeysecret, exchange } = createAccountDto;
    if (await this.findByApikeyAndSecret(apikey, apikeysecret)) {
      throw new HttpException(
        'Account with these api key and api key secret already exists',
        HttpStatus.UNPROCESSABLE_ENTITY,
      );
    }

    const account = new Account();
    account.apikey = apikey;
    account.apikeysecret = apikeysecret;
    account.exchange = exchange;
    account.useruser = user;

    await this.accountRepository.save(account);

    // return await this.accountRepository.save({
    //   ...createAccountDto,
    //   user,
    // });
  }

And it insert always NULL foreign key userId. How can I solve it ?

Upvotes: 4

Views: 1861

Answers (1)

Peter MAY
Peter MAY

Reputation: 21

I had the same problem and fixed it by:

  • creating a new instance of the account entity
  • then updating user on that entity
  • then saving it to the database.

My database finally had a userid instead of null.

@Injectable()
export class AccountsService {
  constructor(
    @InjectRepository(AccountsEntity)
    private readonly accountsRepo: Repository<AccountsEntity>,
    @InjectRepository(UserEntity)
    private userRepo: Repository<UserEntity>,
  ) {}

  async create(account: CreateAccountDTO, userEmail: string) {
    const user = await this.userRepo.findOneBy({ email: userEmail });
    if (!user) return 'Problems!!!!';
    if (user) {
      const newAcc = this.accountsRepo.create(account);

      newAcc.user = user;

      this.accountsRepo.save(newWO);
      return foo;
    }
  }
}

Upvotes: 0

Related Questions