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.

Similar Reads

Transactions in Mongoose

Step 1: First, make sure you have Mongoose installed and import it into your Node.js application:...

Transactions with Mongoose Documents

Mongoose makes it easy to work with transactions when dealing with documents. If you retrieve a Mongoose document using a session, the document will automatically use that session for save operations. You can use doc.$session() to get or set the session associated with a specific document....

Transactions with the Aggregation Framework

...

Advanced Usage and Manual Transaction Control

Mongoose’s Model.aggregate() function also supports transactions. You can use the session() helper to set the session option for aggregations within a transaction. This is useful when you need to perform complex aggregations as part of a transaction....