Search code examples
typescriptnestjstypeorm

How do I get this one to one relationship working on legacy tables?


I am trying to link two legacy user tables together while writing a web application (angular, nestjs, typeorm) for our existing system. However, I keep getting a variation on the error "TypeORMError: Referenced column userid was not found in entity Foruser"

This is the authentication table, that used to contain things like the users password.

@Index("pk_foruser", ["id"], { unique: true })
@Entity("foruser", { schema: "dbo" })
export class Foruser {
  @PrimaryColumn("varchar", { name: "id", length: 28 })
  id: string;

  @OneToOne(() => Adbuinfo)
  Profile: Relation<Adbuinfo>;
}

This is the User profile table, that contains the permissions and app details.


@Index("pk_adbuinfo", ["userid"], { unique: true })
@Entity("adbuinfo", { schema: "dbo" })
export class Adbuinfo {
  @PrimaryColumn("varchar", {  name: "userid", length: 32 })
  userid: string;

  @OneToOne(() => Foruser, (Foruser) => Foruser.Profile, { cascade: true})
  @JoinColumn({name: 'id', referencedColumnName: 'id'})
  User: Relation<Foruser>;
}

I can't just change the column names for the primary key, as we have other applications that used these tables.

Edit: this is the full stack trace of the error.

TypeORMError: Referenced column userid was not found in entity Foruser
    at C:\Development\Web Adtakr-1\adtakr-service\src\metadata-builder\RelationJoinColumnBuilder.ts:151:27
    at Array.map (<anonymous>)
    at RelationJoinColumnBuilder.collectReferencedColumns (C:\Development\Web Adtakr-1\adtakr-service\src\metadata-builder\RelationJoinColumnBuilder.ts:143:32)
    at RelationJoinColumnBuilder.build (C:\Development\Web Adtakr-1\adtakr-service\src\metadata-builder\RelationJoinColumnBuilder.ts:62:40)
    at C:\Development\Web Adtakr-1\adtakr-service\src\metadata-builder\EntityMetadataBuilder.ts:180:60
    at Array.forEach (<anonymous>)
    at C:\Development\Web Adtakr-1\adtakr-service\src\metadata-builder\EntityMetadataBuilder.ts:173:22
    at Array.forEach (<anonymous>)
    at EntityMetadataBuilder.build (C:\Development\Web Adtakr-1\adtakr-service\src\metadata-builder\EntityMetadataBuilder.ts:166:14)
    at ConnectionMetadataBuilder.buildEntityMetadatas (C:\Development\Web Adtakr-1\adtakr-service\src\connection\ConnectionMetadataBuilder.ts:106:11)

If I change the name and/or referencedColumnName to userid, or leave the join column empty, then the error just changes to cannot find userid in Foruser.


Solution

  • I have discovered the source of my issue. I got tunnel vision and was focused on only those two tables. The issue was in a third entity that had a one to many relationship with Foruser.

    For people who are looking at this question in the future (assuming a mod doesn't delete it). Remember that the problem may not be where you think it is.