TypeORM's Soft Delete feature allows marking records as deleted instead of physically deleting them:
-
Enable soft delete: Use the @DeleteDateColumn() decorator in the entity:
typescript@Entity() export class User { @DeleteDateColumn() deletedAt?: Date; } -
Soft delete operations:
typescriptawait userRepository.softRemove(user); // or use await userRepository.softDelete(userId); -
Restore soft-deleted records:
typescriptawait userRepository.restore(userId); -
Exclude soft-deleted records when querying: By default, the find() method automatically excludes soft-deleted records.
-
Include soft-deleted records:
typescriptuserRepository.find({ withDeleted: true }); -
Query only soft-deleted records:
typescriptuserRepository.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.