Skip to content

Instantly share code, notes, and snippets.

@luisfranciscocesar
Forked from aeciolevy/Example.js
Created December 29, 2020 22:05
Show Gist options
  • Save luisfranciscocesar/ebeb66e0d0422da9eb034fe6a0f9680f to your computer and use it in GitHub Desktop.
Save luisfranciscocesar/ebeb66e0d0422da9eb034fe6a0f9680f 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