Skip to content

Is it possible to initialize an entity with a config object? #3903

Closed

Description

@bennycode

Issue type:

[x] question
[ ] bug report
[ ] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[ ] postgres
[ ] cockroachdb
[x] sqlite
[ ] sqljs
[ ] react-native
[ ] expo

TypeORM version:

[ ] latest
[ ] @next
[x] 0.2.15

Steps to reproduce or a small repository showing the problem:

I modified the sample which comes with:

typeorm init --name MyProject --database sqlite

In the original setup a user is created like this:

const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.age = 25;

Unfortunately this doesn't work well when you use "strict": true in your tsconfig.json because it will throw the following error:

error TS2564: Property 'firstName' has no initializer and is not definitely assigned in the constructor.

To avoid the above error I tried passing an object to User:

const user = new User({
  firstName: "Timber",
  lastName: "Saw",
  age: 25
});

I also updated the User.ts file:

import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  age: number;

  constructor(params: { firstName: string, lastName: string, age: number }) {
    this.id = 0;
    this.firstName = params.firstName;
    this.lastName = params.lastName;
    this.age = params.age;
  }
}

When I now run the program, I receive the following error:

TypeError: Cannot read property 'firstName' of undefined
at new User (D:\Temp\MyProject\src\entity\User.ts:20:29)
at EntityMetadata.create (D:\Temp\MyProject\src\metadata\EntityMetadata.ts:500:19)
at EntityMetadataValidator.validate (D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:111:47)
at D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:44:56
at Array.forEach ()
at EntityMetadataValidator.validateMany (D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:44:25)
at Connection.buildMetadatas (D:\Temp\MyProject\src\connection\Connection.ts:508:33)
at Connection. (D:\Temp\MyProject\src\connection\Connection.ts:189:18)
at step (D:\Temp\MyProject\node_modules\tslib\tslib.js:133:27)
at Object.next (D:\Temp\MyProject\node_modules\tslib\tslib.js:114:57)

How come that firstName is undefined? In my code I never call new User without a configuration object.

Is TypeORM doing some magic in the background and calls new User() (without giving it a parameter)?

Activity

  1. abingoal commented on Mar 27, 2019

    @abingoal
    Contributor

    When you use "strict": true in your tsconfig.json, you must modify your entity like this:

    @Entity()
    export class User {
      @PrimaryGeneratedColumn()
      id!: number;
    
      @Column()
      firstName!: string;
    
      @Column()
      lastName!: string;
    
      @Column()
      age!: number;
    }

    just add a bang sign (!).

  2. vlapo commented on Mar 27, 2019

    @vlapo
    Contributor

    Hey @bennyn. In current version constructor parameters have to be optional as it is described in docs (https://typeorm.io/#/entities).

    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.

    But this behaviour is subject of change in next branch. Please see #1772, #3845.

    Closing as this is changed in next.

  3. bennycode commented on Mar 27, 2019

    @bennycode
    Author

    @vlapo Thanks for the info and linking the tickets.

    I updated my TypeORM version to "next" (which resulted in getting "0.3.0-alpha.23") but I am still seeing the same error:

    TypeError: Cannot read property 'firstName' of undefined
    at new User (D:\Temp\MyProject\src\entity\User.ts:19:29)
    at EntityMetadata.create (D:\Temp\MyProject\src\metadata\EntityMetadata.ts:505:19)
    at EntityMetadataValidator.validate (D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:111:47)
    at D:\Temp\MyProject\src\metadata-builder\EntityMetadataValidator.ts:44:56

    Can I file a bug for "next" then because the PR (#3845) seems to be already in?

  4. vlapo commented on Mar 27, 2019

    @vlapo
    Contributor

    Its just 8 days from merge. You have to wait to new release of next branch.

  5. colthreepv commented on Apr 19, 2019

    @colthreepv

    I also am facing an ugly problem when adding ! not-null assertions in entity files #4018

    hope next release might be expedited

  6. bennycode commented on Oct 16, 2019

    @bennycode
    Author

    @vlapo I tested with typeorm v0.3.0-alpha.24 and it works now. Thank you very much! 🥳

    Here is my full test code for people finding this issue:

    initDatabase.ts

    import 'reflect-metadata';
    import {Connection, createConnection} from 'typeorm';
    import {SqliteConnectionOptions} from 'typeorm/driver/sqlite/SqliteConnectionOptions';
    import {PostgresConnectionOptions} from 'typeorm/driver/postgres/PostgresConnectionOptions';
    import {User} from './entity/User';
    
    export default function initDatabase(): Promise<Connection> {
      const localhost: SqliteConnectionOptions = {
        database: 'test.db3',
        type: 'sqlite'
      };
    
      const production: PostgresConnectionOptions = {
        type: 'postgres',
        url: process.env.DATABASE_URL
      };
    
      const connectionOptions = (process.env.NODE_ENV === 'production') ? production : localhost;
    
      Object.assign(connectionOptions, {
        entities: [
          User
        ],
        logging: false,
        migrations: [
          'src/migration/**/*.ts'
        ],
        subscribers: [
          'src/subscriber/**/*.ts'
        ],
        synchronize: true,
      });
    
      return createConnection(connectionOptions);
    };

    User.ts

    import {BaseEntity, Column, Entity, PrimaryGeneratedColumn} from "typeorm";
    
    @Entity()
    export class User extends BaseEntity {
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column()
      firstName: string;
    
      @Column()
      lastName: string;
    
      @Column()
      age: number;
    
      constructor(params: { firstName: string, lastName: string, age: number }) {
        super();
        this.id = 0;
        this.firstName = params.firstName;
        this.lastName = params.lastName;
        this.age = params.age;
      }
    }

    index.ts

    import initDatabase from "./initDatabase";
    import {User} from "./entity/User";
    
    (async () => {
      await initDatabase();
      const user = new User({
        firstName: "Timber",
        lastName: "Saw",
        age: 25
      });
      await user.save();
    })();
  7. mishabruml commented on Jun 16, 2022

    @mishabruml

    This may help you #4464 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions