DEV Community

Kazi Abdur Rakib
Kazi Abdur Rakib

Posted on

Implement transaction & rollback

const session = await mongoose.startSession();
try {
  session.startTransaction();
  const newUser = await User.create([userData], { session }); // array
  await session.commitTransaction();
  await session.endSession();
} catch (err: any) {
  await session.abortTransaction();
  await session.endSession();
  throw new AppError(httpStatus.NOT_FOUND, err);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
rajeshroyal profile image
Rajesh Royal

nice article, one suggestion
you can end session in finally block

finally{
// end session
}

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay