Multi-statement transactions are a big deal for a lot of companies. The transactions feature has been in development since MongoDB version 3.6 when sessions were added. Now we will be able to see how both sessions and transactions work. here is the article, we highlighted a few details from what was delivered in 3.6 that indicated that 4.0 would have transactions.
MongoDB currently only supports transactions on replica sets, not standalone servers. To run a local replica set for development on macOS, Linux or Windows, use npm to install run-rs globally and run run-rs --version 4.0.0
. Run-rs will download MongoDB 4.0.0 for you.
To use transactions with Mongoose, you should use Mongoose >= 5.2.0
. To check your current version of Mongoose, run npm list | grep "mongoose"
or check the mongoose.version
property.
Transactions are built on MongoDB sessions. To start a transaction, you first need to call startSession()
and then call the session’s startTransaction()
function. To execute an operation in a transaction, you need to pass the session
as an option.
We have to Set Replica in Mongodb (Atlas By Default provide this feature).
Transaction:
var session = await mongoose.startSession({
readPreference: { mode: ‘primary’ }
});
session.startTransaction();
try{
user = new User();
user.first_name = ‘john’;
user.last_name = ‘smith’;
//pass session when data is saved.
let userdata = await user.save({session});
//commit transcation when all process is done
await session.commitTransaction();
session.endSession();
}catch(){
await session.abortTransaction();
session.endSession();
}