'ERROR [ExceptionsHandler] Cannot read properties of null (reading 'concat')

Here What I did is I have a user entity and a role entity. Every user can have one role. I have set up many-one relationship in role entity. I have create an endpoint from which I can link user with its role but I am facing the error mentioned above.

Role Entity

@Entity()
export class Role extends BaseTable {
  @Column({
    type: 'enum',
    enum: RoleType,
    name: 'role_type',
  })
  roleType: RoleType;

  @Column({ name: 'description' })
  description: string;
  entitlement: any;

  @ManyToMany(() => Entitlement, { eager: true })
  @JoinTable({
    name: 'role-entitlements',
    joinColumn: {
      name: 'role_id',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'entitlement_id',
      referencedColumnName: 'id',
    },
  })
  entitlements: Entitlement[];

  @ManyToOne(() => User, { eager: true })
  @JoinColumn({ name: 'user_id' })
  users: User[];

  @ManyToOne(() => Company, (company) => company.roles)
  @JoinColumn({ name: 'company_id' })
  company: Company;
}

Function created to link user-role:

  async addRole(id: string, addRoleDto: AddRoleDto) {
    const currUser: User = await this.findAndValidateUser(id);
    const role: Role = await this.rolesService.findAndValidateRole(
      addRoleDto.roleId,
    );
    currUser.role = role.roleType;
    console.log(role.users);
    role.users = role.users.concat(currUser);
    await this.rolesRepository.save(role);
  }

Role Table in database: enter image description here

When I set a role in the database by default the userid has null values. so when a user is set to a certain role the function has to replace null with user.



Solution 1:[1]

role.users = role.users? role.users.concat(currUser) : [currUser]

Hope this helps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sathya