'Cannot read properties of undefined (reading 'concat')
Roles entity has many-many relation with entitlement entity as shown below:
@ManyToMany(() => Entitlement)
@JoinTable({
name: 'role-entitlements',
joinColumn: {
name: 'role_id',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'entitlement_id',
referencedColumnName: 'id',
},
})
entitlements: Entitlement[];
Below given is the function to add multiple entitlements to a Role:
async linkEntitlement(id: string, linkEntitlementDto: LinkEntitlementDto) {
const role: Role = await this.findOne(id);
if (!role) {
throw new CustomException('role not found');
}
const entitlement: Entitlement = await this.entitlementService.findOne(
linkEntitlementDto.entitlementId,
);
if (!entitlement) {
throw new CustomException('entitlement not found');
}
const entitlements: Entitlement[] = role.entitlements;
role.entitlements = entitlements.concat(entitlement);
await this.rolesRepository.save(role);
}
Below given is the json content I am trying to post via Postman:
{
"entitlements":[
{"id":"12d7b37e-1464-4ffa-b9af-779ab298afb9"}
]
}
I am getting the error as mentioned above What I am trying to do here is there's an Role entity and an entitlement entity. I created many- many relationship between role and entitlement. I created a function LinkEntitlement where I can map role & entitlement. I am posting the data via postman here but I am facing such an error. What is it that I can change in this code?below is the postman image
Solution 1:[1]
entitlements is undefined because you didn't fetch the relationship with Entitlement and it is lazily loaded by default.
To do so:
const role = await this.findOne(id, { relations: ['entitlements'] });
btw I advise you to mark that field entitlements: Entitlement[] as optional. Then you won't get confused on why TypeScript is telling you that something is not undefined when it is at runtime.
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 | Micael Levi |
