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
}