Search code examples
node.jstypeormnode.js-typeorm

Node.js add created_at and updated_at in entity of typeorm


I have task entity like this:

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

@Entity()
export class Task extends BaseEntity{
    @PrimaryGeneratedColumn()
    id:number;

    @Column()
    title:string

   @Column()
    description:string

}

I want to add created_at and updated_at field to this entity and populate it automatically with Node.js like Laravel framework. My database is postgres


Solution

  • Let's import first

    import { CreateDateColumn,UpdateDateColumn } from "typeorm";
    

    Add this fields and decarators in Entity

    @CreateDateColumn({ type: "timestamp", default: () => "CURRENT_TIMESTAMP(6)" })
    public created_at: Date;
    
    @UpdateDateColumn({ type: "timestamp", default: () => "CURRENT_TIMESTAMP(6)", onUpdate: "CURRENT_TIMESTAMP(6)" })
    public updated_at: Date;