Search code examples
typescriptmigrationtypeorm

TypeORM: Cannot read property 'id' of undefined


I tried to using mirgation in TypeORM like this:

TableExample.entity.ts

@Entity({ name: 'table_example' })
export class TableExampleEntity {

    constructor(properties : TableExampleInterface) {
        this.id = properties.id;
    }

    @PrimaryColumn({
        name: 'id',
        type: 'uuid',
        generated: 'uuid',
        default: 'uuid_generate_v4()',
    })
    id? : string;

}

TableExample.interface.ts

export interface TableExampleInterface{
    id? : string;
}

and migration file

import {MigrationInterface, QueryRunner, Table} from 'typeorm';

export class createSongEntities1591077091789 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.createTable(new Table({
            name: 'table_example',
            columns: [
                {
                    name: 'id',
                    type: 'uuid',
                    generationStrategy: 'uuid',
                    default: 'uuid_generate_v4()',
                    isPrimary: true,
                },
            ],
        }));
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.dropTable('table_example');
    }

}

When run mirgation, node server thrown this error Stack trace

Error during migration run:
TypeError: Cannot read property 'id' of undefined
    at new TableExampleEntity (...\src\entities\TableExample.entity.ts:17:34)
    at EntityMetadata.create (...\src\metadata\EntityMetadata.ts:524:19)
    at EntityMetadataValidator.validate (...\src\metadata-builder\EntityMetadataValidator.ts:112:47)  
    at ...\src\metadata-builder\EntityMetadataValidator.ts:45:56
    at Array.forEach (<anonymous>)
    at EntityMetadataValidator.validateMany (...\src\metadata-builder\EntityMetadataValidator.ts:45:25)
    ...

What wrong at here? Please help me!


Solution

  • From typeorm documentation here:

    When using an entity constructor its arguments must be optional. Since ORM creates instances of entity classes when loading from the database, therefore it is not aware of your constructor arguments.

    What happens in your case is typeorm is creating an instance of the entity and is not passing anything in the constructor. So properties parameter is undefined.