乐闻世界logo
搜索文章和话题

How to implement soft delete in TypeORM?

2月17日 22:43

TypeORM's Soft Delete feature allows marking records as deleted instead of physically deleting them:

  1. Enable soft delete: Use the @DeleteDateColumn() decorator in the entity:

    typescript
    @Entity() export class User { @DeleteDateColumn() deletedAt?: Date; }
  2. Soft delete operations:

    typescript
    await userRepository.softRemove(user); // or use await userRepository.softDelete(userId);
  3. Restore soft-deleted records:

    typescript
    await userRepository.restore(userId);
  4. Exclude soft-deleted records when querying: By default, the find() method automatically excludes soft-deleted records.

  5. Include soft-deleted records:

    typescript
    userRepository.find({ withDeleted: true });
  6. Query only soft-deleted records:

    typescript
    userRepository.find({ withDeleted: true, where: { deletedAt: Not(IsNull()) } });

The advantage of soft delete is that it preserves data history, making it easier to recover data and conduct audits.

标签:TypeORM