Prisma ORM Soft Delete and Flag Usage


Prisma ORM Soft Delete and Flag Usage

Prisma ORM has become a popular choice for data management and modeling in modern Node.js projects. Especially when it comes to deleting records from the database, the use of "soft delete" and "flag" is critically important for preserving data integrity. This technique allows marking a record as deleted without actually removing it completely, enabling it to be restored if necessary. In this article, we will cover with examples how to design soft delete architecture and the flag logic using Prisma ORM.

What are the Concepts of Soft Delete and Flag?

Soft delete means marking a database record as "deleted" using a specific column (usually deletedAt or isDeleted) rather than physically deleting it. Flag usage, on the other hand, refers to adding special fields to indicate a specific state on the data (such as active/inactive, deleted/not deleted). With these methods, you reduce the risk of unintentionally losing records in your application, and you also make audit and recovery operations easier.

How to Apply Soft Delete with Prisma ORM?

To implement soft delete with Prisma ORM, you need to define an extra field in your model to be used as a "flag". You can see a sample user model below:

model User {
  id         Int      @id @default(autoincrement())
  email      String   @unique
  name       String?
  deletedAt  DateTime?
  // Alternatively: isDeleted Boolean @default(false)
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt
}

Here, if the deletedAt field is null, the user is active; if it has a value, the user is considered soft deleted (i.e., deleted).

Deletion Process and Update

The example below shows how to delete a user with soft delete:

// Soft delete the user
await prisma.user.update({
  where: { id: 1 },
  data: { deletedAt: new Date() }
});

Here, instead of using delete directly, we used update and assigned a date to deletedAt. In this way, the data still continues to be stored in the database.

Filtering Records with Flag

To exclude soft deleted users when fetching active users, you write a query like this:

// Get the users who are not deleted
const users = await prisma.user.findMany({
  where: {
    deletedAt: null
  }
});

Alternatively, you can also filter with a Boolean flag as isDeleted: false.

Conclusion: Why Should You Use Soft Delete?

Prisma ORM Soft Delete and Flag Usage is extremely useful to prevent data loss, and to provide possibilities for rollback and auditing. Especially in corporate projects, it offers an important advantage for legal responsibilities and user experience. With an effective soft delete strategy, your software becomes more secure, flexible, and sustainable.