Databases

TypeORM vs Prisma in NestJS: what are the differences?

TypeORMPrisma
ModelsDecorated entity classesschema.prisma file
QueriesRepository / QueryBuilderGenerated, fully typed client
Type safety of resultsPartial (relations not reflected in types)Strong (includes/selects change the type)
MigrationsGenerated from entity diffprisma migrate from schema diff
Nest integration@nestjs/typeorm, @InjectRepositoryYour own PrismaService extends PrismaClient

Why should synchronize be false in production?

synchronize: true makes TypeORM alter the schema to match entities on every start. A renamed property becomes DROP COLUMN + ADD COLUMN and silently deletes data, and there is no review or rollback. In production use migrations: generate, review, commit, run them in the deploy pipeline (migration:run or prisma migrate deploy).

How do you prevent overselling the last item when two orders arrive at the same time?

Do the check and the update in one atomic statement inside a transaction: UPDATE products SET stock = stock - $qty WHERE id = $id AND stock >= $qty and treat 0 affected rows as out of stock (Prisma: updateMany with stock: { gte: qty } and check count). Alternatives: pessimistic lock (SELECT ... FOR UPDATE) or optimistic locking with a version column. A "read, check in JS, then write" approach has a race condition.

How do you run several writes in a transaction with Prisma and TypeORM?

// Prisma: interactive transaction, use tx inside
await this.prisma.$transaction(async (tx) => {
  const order = await tx.order.create({ data: { userId, total } });
  await tx.payment.create({ data: { orderId: order.id, amount: total } });
});

// TypeORM: DataSource.transaction gives an EntityManager
await this.dataSource.transaction(async (manager) => {
  const order = await manager.save(Order, { user: { id: userId }, total });
  await manager.save(Payment, { order, amount: total });
});

If the callback throws, everything is rolled back. Do not call external APIs (payment gateway) inside a DB transaction; keep transactions short.