When using TypeORM, adding created_at and updated_at fields automatically to entities is a common requirement. These fields record the creation time and most recent update time of data. The method to implement these fields is as follows:
1. Defining the Entity
First, define an entity where you will add created_at and updated_at fields. These fields can be automatically managed using TypeORM decorators.
typescriptimport { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @CreateDateColumn({ type: 'timestamp', name: 'created_at' }) createdAt: Date; @UpdateDateColumn({ type: 'timestamp', name: 'updated_at' }) updatedAt: Date; }
2. Using CreateDateColumn and UpdateDateColumn
As shown in the code above, we utilize the CreateDateColumn and UpdateDateColumn decorators:
- The CreateDateColumn decorator automatically sets and updates the created_at field. This field is initialized only once during the first save operation.
- The UpdateDateColumn decorator automatically sets and updates the updated_at field. This field is refreshed every time the entity is modified.
3. Configuring the Database
Ensure your database supports timestamp fields. Most modern database systems (such as PostgreSQL, MySQL, and SQLite) natively support automatic timestamps.
4. Using Entities for Operations
When creating or updating entities, TypeORM automatically handles these fields. For example:
typescriptimport { getRepository } from 'typeorm'; import { User } from './User'; async function createUser() { const userRepository = getRepository(User); const newUser = userRepository.create({ name: 'John Doe' }); await userRepository.save(newUser); console.log(newUser); } async function updateUser(userId: number) { const userRepository = getRepository(User); const userToUpdate = await userRepository.findOne(userId); if (userToUpdate) { userToUpdate.name = 'Jane Doe'; await userRepository.save(userToUpdate); console.log(userToUpdate); } }
In this example, calling the save method automatically updates both created_at and updated_at fields. Manual handling of these fields is unnecessary.
Conclusion
Using TypeORM's CreateDateColumn and UpdateDateColumn decorators provides a straightforward way to manage record creation and update timestamps, enabling better tracking of data change history.