Skip to content

Instantly share code, notes, and snippets.

@aeciolevy
Created March 3, 2019 17:18
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save aeciolevy/0962ad4ee45f340cbac0622e089030b3 to your computer and use it in GitHub Desktop.
Save aeciolevy/0962ad4ee45f340cbac0622e089030b3 to your computer and use it in GitHub Desktop.
Example of mongoose transaction. MongoDB transaction example
exports.deleteUser = async (req, res, next) {
const session = await mongoose.startSession();
try {
const { id } = req.params;
// Start session
await session.startTransaction();
// deleteMany in this session
const [errorOp, result] = await toAll([App.deleteMany({ user: id }).session(session), UserModel.findByIdAndRemove(id).session(session)]);
if (errorOp) {
throw new ErrorRequest(STATUS_CODE.UNPROCESSABLE, errorOp.message);
}
const [app, user] = result;
// if does not found user throw an error
if (!user) {
throw new ErrorRequest(STATUS_CODE.BAD_REQUEST, 'User not found.');
}
// delete user if delete apps succeed
const { password, ...deletedUser } = user;
// finish transcation
await session.commitTransaction();
session.endSession();
return res.send({ status: 'User deleted', ...deletedUser, appDeletedCount: app.deletedCount });
} catch (err) {
await session.abortTransaction();
session.endSession();
next(err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment