-
-
Save luisfranciscocesar/3a36233db680ff9d9986eae515833896 to your computer and use it in GitHub Desktop.
Example of mongoose transaction. MongoDB transaction example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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