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
In TypeORM, you can add a created_at column and a updated_at column by making use of the CreateDateColumn and UpdateDateColumn decorators, respectively. These columns will be automatically initialized and updated to the current date and time (that is, the current timestamp).
To follow the DRY ( Don’t-Repeat-Yourself) principle, TypeORM gives us the luxury of creating entities that inherit the columns of a base entity. TypeORM also comes with a defined BaseEntity that we can extend to have access to the various attributes and methods we can use to perform CRUD operations.
TypeORM – an ORM (Object Relational Mapping) for popular Database services like PostgreSQL, MySQL, MongoDB, and many more. We’ll build a REST API where we can create, read, update and delete a post in the database. To test the API endpoints, am going to use HTTP Client VS Code extension .
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;
import {BaseEntity, Column, Entity, PrimaryGeneratedColumn, CreateDateColumn} from "typeorm";
@Entity()
export class Task extends BaseEntity{
@PrimaryGeneratedColumn()
id:number;
@Column()
title:string
@Column()
description:string
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
import { CreateDateColumn, UpdateDateColumn } from 'typeorm';
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
I tried all the previous ways you informed, but the only way that worked was this.
import moment from "moment";
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@BeforeInsert()
insertCreated() {
this.created_at = new Date(
moment().tz("America/Sao_Paulo").format("YYYY-MM-DD HH:mm:ss")
);
this.updated_at = new Date(
moment().tz("America/Sao_Paulo").format("YYYY-MM-DD HH:mm:ss")
);
}
@BeforeUpdate()
insertUpdated() {
this.updated_at = new Date(
moment().tz("America/Sao_Paulo").format("YYYY-MM-DD HH:mm:ss")
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With