Transactions in Mongoose
Step 1: First, make sure you have Mongoose installed and import it into your Node.js application:
import mongoose from 'mongoose';
Step 2: Create a Session, Transactions in Mongoose are managed through sessions. You can create a session using either the default Mongoose connection or a custom connection:
// Using the default Mongoose connection
const session = await mongoose.startSession();
// Using a custom connection
const db = await mongoose.createConnection(mongodbUri).asPromise();
const session = await db.startSession();
Step 3: Perform Transactions, Once you have a session, you can perform transactions using the session.withTransaction() helper or Mongoose’s Connection#transaction() function. These functions simplify the transaction management process.
let session = null;
return Customer.createCollection()
.then(() => Customer.startSession())
.then(_session => {
session = _session;
return session.withTransaction(() => {
return Customer.create([{ name: 'Test' }], { session: session });
});
})
.then(() => Customer.countDocuments())
.then(count => console.log(`Total customers: ${count}`))
.then(() => session.endSession());
Transactions in Mongoose
Mongoose Transactions allows to execute multiple database operations within a single transaction, ensuring that they are either all successful or none of them are. Mongoose provides powerful tools to manage transactions effectively.