I have a Project entity with a non-autogenerated id field and a successor field. This successor is the project that follows next. But maybe there is no following project so this might be null.
@Entity()
export class Project extends BaseEntity {
@PrimaryColumn({ unique: true })
public id: string;
@OneToMany(() => Project, project => project.id, { nullable: true })
public successorId?: string;
}
When creating a new project via
public createProject(id: string, successorId?: string): Promise<Project> {
const project: Project = new Project();
project.id = id;
project.successorId = successorId;
return project.save();
}
there are multiple cases I have to take care for.
Passing in an id that already exists:
This will not throw an error. It just overrides the existing entity.
Passing in
undefinedfor thesuccessorId:The code works fine then but it does not create a
successorIdcolumn withnullthen. The column simply does not exist in the database.Passing in the same id for
idandsuccessorId(this should be possible):TypeORM throws the error
TypeError: Cannot read property 'joinColumns' of undefined
Passing in a
successorIdof another existing project:I'm getting the same error as above
Passing in a
successorIdof a project that doesn't exist:I'm getting the same error as above
So how can I fix that? I think my entity design seems to be wrong. Basically it should be
- One project might have one successor
- A project can be the successor of many projects
Would be awesome if someone could help!
Update
I also tried this
@OneToMany(() => Project, project => project.successorId, { nullable: true })
@Column()
public successorId?: string;
but whenever I want to call the createProject method I'm getting this error
QueryFailedError: null value in column "successorId" violates not-null constraint
and this
@OneToMany(() => Project, project => project.successorId, { nullable: true })
public successorId?: string;
but then I'm getting this error
TypeError: relatedEntities.forEach is not a function