I have a typical transaction operation using mongoose in my nodeJS/Express application:
let session = null;
try {
session = await mongoose.startSession();
await User.create({ ... });
await Otp.create({ ... });
await session.commitTransaction();
}
catch (error) {
await session.abortTransaction();
}
finally {
session.endSession();
}
However, I have learned that both abortTransaction()
and endSession()
can throw errors, which is why I wonder what happens when these operations fail? Will mongoose clean up the mess by itself? Or do I need to periodically re-attempt to abort the transaction/end the session until it works or some other weird stuff like that? Can't seem to find any information about how to handle this as every tutorial I see just leave the code the way I wrote it in the code block above without even wrapping the abort or end calls in their own try catches.
I have learned that both
abortTransaction()
andendSession()
can throw errors, which is why I wonder what happens when these operations fail?
abortTransaction()
will throw an error only when you attempt to abort a transaction that has been commited already or when no transaction is alive.
Refer
endSession()
won't throw any error. Refer
The abortTransaction()
will only throw an error, when your code be like this.
try {
session = await mongoose.startSession();
//...
await session.commitTransaction();
await session.abortTransaction();
}
catch (error) {
await session.abortTransaction();
}
Or:
try {
session = await mongoose.startSession();
//...
await session.abortTransaction();
} catch (err) {
console.log(err);
}
Proper usage is the key here.