Bird
0
0

You want to update two related entities atomically in NestJS using TypeORM transactions. Which approach correctly ensures both updates succeed or fail together?

hard📝 Application Q15 of 15
NestJS - Database with TypeORM
You want to update two related entities atomically in NestJS using TypeORM transactions. Which approach correctly ensures both updates succeed or fail together?
async updateEntities(entityA, entityB) {
  await this.dataSource.transaction(async (manager) => {
    await manager.save(entityA);
    await manager.save(entityB);
  });
}
What is the best practice to handle errors and maintain data consistency?
AManually call rollback() inside the transaction callback on error
BSave entities without transactions and rely on database constraints
CUse separate transactions for each save to isolate failures
DWrap the transaction call in try-catch and handle rollback automatically
Step-by-Step Solution
Solution:
  1. Step 1: Understand transaction error handling in TypeORM

    TypeORM automatically rolls back if an error is thrown inside the transaction callback.
  2. Step 2: Use try-catch outside transaction to handle errors

    Wrapping the transaction call in try-catch lets you catch errors and respond without manual rollback calls.
  3. Final Answer:

    Wrap the transaction call in try-catch and handle rollback automatically -> Option D
  4. Quick Check:

    Try-catch outside transaction handles errors; rollback is automatic [OK]
Quick Trick: Use try-catch around transaction; rollback is automatic [OK]
Common Mistakes:
  • Trying to manually rollback inside transaction callback
  • Using separate transactions for related updates
  • Ignoring transactions and relying only on DB constraints

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes