question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

@CreateDateColumn does not auto populate upon insertion.

See original GitHub issue

Issue type:

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

Database system/driver:

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

TypeORM version:

[ ] latest [ ] @next [x] 0.2.2

Steps to reproduce or a small repository showing the problem:

Sample entity definition.

export class MyEntity {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column({type: "int"})
    public password_reset_id: number;

    @Column({type: "varchar"})
    public password_hash: string;

    @CreateDateColumn()
    public created_at: Date;

    @UpdateDateColumn()
    public updated_at: Date;

    @Column({type: "timestamp"})
    public deleted_at: Date;
}

It would seem that after updating to version 0.2.2 my created_at columns are no longer being populated upon record insertion. Has the @CreateDateColumn() decorator changed in someway? Am I missing something completely obvious?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:13 (5 by maintainers)

github_iconTop GitHub Comments

4reactions
mrsauravsahucommented, Jun 18, 2020

you can try

@CreateDateColumn({ default: () => 'NOW()' })
createdAt: Date

in your entity. This should generate the right migration.

0reactions
mrsauravsahucommented, Jul 7, 2022

you can try

@CreateDateColumn({ default: () => 'NOW()' })
createdAt: Date

in your entity. This should generate the right migration.

i have tried this and it did not work either

Odd, tried this again. I’m still able to generate the right migration.

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

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number

    @CreateDateColumn({ default: () => 'NOW()' })
    createdAt: Date
}
npm run typeorm -- migration:generate src/migration/InitialCreate -d src/data-source.ts

which generated this migration

import { MigrationInterface, QueryRunner } from "typeorm";

export class InitialCreate1657194989813 implements MigrationInterface {
    name = 'InitialCreate1657194989813'

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`CREATE TABLE "user" ("id" SERIAL NOT NULL, "firstName" character varying NOT NULL, "lastName" character varying NOT NULL, "age" integer NOT NULL, "createdAt" TIMESTAMP NOT NULL DEFAULT NOW(), CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`DROP TABLE "user"`);
    }

}
import "reflect-metadata"
import { AppDataSource } from "./data-source"
import { User } from "./entity/User"

AppDataSource.initialize().then(async () => {

    console.log("Inserting a new user into the database...")
    const user = new User()
    user.firstName = "Saurav"
    user.lastName = "Sahu"
    user.age = 25
    await AppDataSource.manager.save(user)
    console.log("Saved a new user with id: " + user.id)

    console.log("Loading users from the database...")
    const users = await AppDataSource.manager.find(User)
    console.log("Loaded users: ", users)
}).catch(error => console.log(error))

which fills the createdAt property with the current timestamp

└─$ npm start

> repro-postgres-auto-populate-dates@1.0.0 start
> ts-node src/index.ts

Inserting a new user into the database...
Saved a new user with id: 1
Loading users from the database...
Loaded users:  [
  User {
    id: 1,
    firstName: 'Saurav',
    lastName: 'Sahu',
    age: 25,
    createdAt: 2022-07-07T06:27:59.987Z
  }
]
Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I create columns with type Date and type DateTime ...
Moreover, automatic dates for certain events are possible: Creation Date, available via @CreateDateColumn() decorator.
Read more >
Decorator reference - typeorm - GitBook
If not specified, then table name is generated from entity class name. ... Special column that is automatically set to the entity's insertion...
Read more >
typeorm/typeorm - Gitter
Let's say I want to manually create a new object of the below Photo class. How do I create a new entity that...
Read more >
Generated Values - EF Core - Microsoft Learn
On relational databases, a column can be configured with a default value; if a row is inserted without a value for that column, ......
Read more >
Adding A Created Date And Modified Date Column To A Table ...
The value of the created date column will be set when the record is ... we'll need to create a trigger on the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found