The Wayback Machine - https://web.archive.org/web/20240906164748/https://www.geeksforgeeks.org/transactions-in-mongoose/
Open In App

Transactions in Mongoose

Last Updated : 26 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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 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.

Example: In this example, we work with Mongoose documents within transactions:

  • We create a User model and initiate a session and a user document with the name ‘john’.
  • We start a transaction and use the session for queries, like finding the user with the name ‘john’.
  • We modify the user’s name to ‘smith’ and save the document and confirm that the updated document exists.
  • We commit the transaction and end the session.

Javascript




const UserModel = 
    db.model('User', new Schema({ name: String }));
  
let userSession = null;
return UserModel.createCollection()
    .then(() => db.startSession())
    .then(session => {
        userSession = session;
        const userToCreate = 
            UserModel.create({ name: 'john' });
        return userToCreate;
    })
    .then(() => {
        userSession.startTransaction();
        return UserModel
            .findOne({ name: 'john' }).session(userSession);
    })
    .then(user => {
        assert.ok(user.$session());
        user.name = 'smith';
        return user.save();
    })
    .then(() => UserModel.findOne({ name: 'smith' }))
    .then(result => {
        assert.ok(result);
        userSession.commitTransaction();
        userSession.endSession();
    });


Transactions with the Aggregation Framework

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.

Example: In this example, we use transactions with the Mongoose Aggregation Framework:

  • We create an Event model and initiate a session.
  • We start a transaction and use the session to insert multiple documents into the Event collection.
  • We perform an aggregation operation using Event.aggregate() within the transaction.
  • We commit the transaction and end the session.

Javascript




const EventModel = db.model('Event',
    new Schema({ createdAt: Date }), 'Event');
  
let eventSession = null;
let insertManyResult = null;
let aggregationResult = null;
  
return EventModel.createCollection()
    .then(() => db.startSession())
    .then(session => {
        eventSession = session;
        eventSession.startTransaction();
  
        const documentsToInsert = [
            { createdAt: new Date('2018-06-01') },
            { createdAt: new Date('2018-06-02') },
            // ... other documents ...
        ];
  
        return EventModel.insertMany(documentsToInsert,
            { session: eventSession })
            .then(result => {
                insertManyResult = result;
            });
    })
    .then(() => EventModel.aggregate([
        // Your aggregation pipeline here
    ]).session(eventSession))
    .then(result => {
        aggregationResult = result;
        return eventSession.commitTransaction();
    })
    .then(() => eventSession.endSession())


Advanced Usage and Manual Transaction Control

For advanced users who require more control over when to commit or abort transactions, you can manually start a transaction using session.startTransaction(). This allows you to execute operations within and outside of the transaction as needed. You can also use session.abortTransaction() to manually abort a transaction if needed.

Example: This example demonstrates manual transaction control:

  • We create a Customer model and initiate a session.
  • We start a transaction and use the session for operations like creating a customer.
  • We verify that the customer is not found before committing the transaction.
  • We use the session for further queries, confirming the customer’s existence.
  • We commit the transaction and verify that the customer is still present after the commit. Finally, we end the session.

Javascript




const CustomerModel = db.model('Customer',
    new Schema({ name: String }));
  
let customerSession = null;
let createCustomerResult = null;
let findCustomerResult = null;
  
return CustomerModel.createCollection()
    .then(() => db.startSession())
    .then(session => {
        customerSession = session;
        customerSession.startTransaction();
  
        const customerToCreate = [{ name: 'Test' }];
  
        return CustomerModel.create(customerToCreate,
            { session: customerSession })
            .then(result => {
                createCustomerResult = result;
            });
    })
    .then(() => CustomerModel.findOne({ name: 'Test' }))
    .then(result => {
        findCustomerResult = result;
        assert.ok(!result);
    })
    .then(() => CustomerModel.findOne({ name: 'Test' })
        .session(customerSession))
    .then(doc => {
        assert.ok(doc);
    })
    .then(() => customerSession.commitTransaction())
    .then(() => CustomerModel.findOne({ name: 'Test' }))
    .then(result => {
        assert.ok(result);
    })
    .then(() => customerSession.endSession())
    .then(() => {
        // Now you can access 
        // createCustomerResult and findCustomerResult
        console.log('Create Customer Result:',
            createCustomerResult);
        console.log('Find Customer Result:',
            findCustomerResult);
    });


Conclusion: Transactions in Mongoose provide a powerful mechanism for ensuring data consistency and integrity in your MongoDB-based Node.js applications. By grouping multiple operations into atomic units, you can guarantee that your data remains in a reliable state, even in the face of errors or failures. Whether you’re working with documents, aggregations, or complex operations, Mongoose’s support for transactions makes it easier than ever to build robust and reliable applications on top of MongoDB.



Similar Reads

How to Use MongoDB Transactions in Node.js?
Using MongoDB transactions in Node.js involves several steps. Transactions allow multiple operations on the database to be executed in an all-or-nothing manner, ensuring data consistency. we will learn how to use MongoDB transaction in Node.js. PrerequisitesMongoDB (Version 4.0 or higher Recommended)Replica setSteps to Use MongoDB Transactions in N
2 min read
How to Use Transactions in MySQL with NodeJS?
Transactions in MySQL are used to execute a series of operations as a single unit of work, ensuring that all operations either succeed or fail together. This is crucial in maintaining data integrity, especially when dealing with complex operations that involve multiple database queries. In Node.js, transactions can be implemented using various appr
2 min read
Mongoose Query.prototype.estimatedDocumentCount() API
The estimatedDocumentCount() method is part of the Mongoose Query API and is used to estimate the number of documents in a collection. It provides an approximate count of the documents using metadata, which is faster than counting all documents in the collection. Syntax: const MyModel = mongoose.model('MyModel', mySchema); MyModel.estimatedDocument
3 min read
Mongoose Query.prototype.post() API
The Mongoose Query API post() method is used to add a post middleware to the mongoose query instance, which can be used in performing post-query operations. Syntax: Query.prototype.post(fn) Parameters: It accepts the following parameters as mentioned above and described below: fn: It is a middleware function that is used to perform post-query opera
2 min read
Mongoose Aggregate.prototype.limit() API
The Aggregate API.prototype.limit() function of the Mongoose API is used to limit the number of documents that get passed to the next stage in the aggregator pipeline. Syntax: Aggregate.prototype.limit() Parameters: It accepts a single parameter as described below: num: It is a number that defines the maximum number of documents that get passed to
2 min read
Mongoose SchemaType Options
Mongoose is a common JavaScript library that has a strong interface for operating with MongoDB, a NoSQL database that stores data in JSON-like documents. it's designed to be easy and versatile, creating it easy to work with MongoDB from your Node.js application. In Mongoose, a schema type is a property of a schema that defines the type, required, a
4 min read
Mongoose Schema Connection.prototype.set() API
The Connection.prototype.set() method of the Mongoose API is used on the Connection object. It allows us to set the value for keys in the options object. We can provide the key and its value to the set() method in order to set the options for the connection object. Let us understand the set() method using an example. Syntax: connection.set( <key
2 min read
Mongoose Document Model.prototype.baseModelName API
The Model.prototype.baseModelName property of the Mongoose API is used to return the baseModelName as the name of the base model, if this is a discriminator model, Syntax: Model_Name.baseModelName Return Value: The Model.prototype.baseModelName property returns the baseModelName is the name of the base model, Setting up Node.js application: Step 1:
2 min read
How does Query.prototype.gte() work in Mongoose ?
The Query.prototype.gte() function is used to specify a $gte query condition. It returns documents that are greater than or equal the specified condition. Syntax: Query.prototype.gte() Parameters: This function has one parameter val and an optional parameter path.Return Value: This function returns Query Object. Mongoose Installation: npm install m
2 min read
Mongoose Query prototype.all() API
Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed schema, with default values and schema validations which are later mapped to a MongoDB document. The all( ) method of mongoose Query API is used to find the documents which contain a field that has some specific values. The all() method is used on a field who
3 min read
Mongoose Query.prototype.gte() API
Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed schema, with default values and schema validations which are later mapped to a MongoDB document. This method is used to select those documents where the value of the field is greater than or equal to(>=) the given value. Syntax: Modal.find().where([path]).
3 min read
Mongoose | updateMany() Function
The updateMany() function is same as update(), except MongoDB will update all documents that match the filter. It is used when the user wants to update all documents according to the condition. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose
2 min read
Node.js authentication using Passportjs and passport-local-mongoose
Passport is the authentication middleware for Node. It is designed to serve a singular purpose which is to authenticate requests. It is not practical to store user password as the original string in the database but it is a good practice to hash the password and then store them into the database. But with passport-local-mongoose you don't have to h
5 min read
Mongoose Query API.prototype.writeConcern() Method
The Mongoose Query API.prototype.writeConcern() method of the Mongoose API is used on Query objects. It allows us to set the options for writing events to the database. Using this method we can set various parameters to configure the write operations. Let us understand writeConcern() method using an example. The writeConcern operations are availabl
3 min read
Mongoose | findOneAndDelete() Function
The findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mong
2 min read
Mongoose | deleteOne() Function
The deleteOne() function is used to delete the first document that matches the conditions from the collection. It behaves like the remove() function but deletes at most one document regardless of the single option. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.
2 min read
Mongoose | findByIdAndDelete() Function
The findByIdAndDelete() function is used to find a matching document, removes it, and passing the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your m
2 min read
Mongoose SchemaType.prototype.path Property
The Mongoose SchemaType.prototype.path property of the Mongoose API is used on the SchemaType object. It allows us to get the path or the field of SchemaType in the schema. It can be call on any schema object and is capable of providing path of that particular schema. Let us understand path property using an example. Syntax: schemaTypeObject.path(
3 min read
Mongoose | findOneAndRemove() Function
The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose v
2 min read
Mongoose | findOneAndReplace() Function
The findOneAndReplace() function is used to find a matching element, replaces it with the provided element, and passes the returned doc to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you ca
2 min read
Mongoose | countDocuments() Function
The countDocuments() function is used to count the number of documents that match the filter in a database collection. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose After installing mongoose module, you can check your mongoose version in th
2 min read
Mongoose | exists() Function
The exists() function returns true if at least one document exists in the database that matches the given filter, and false otherwise. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongo
2 min read
Mongoose | where() Function
The where() function is used to create a Query, applies the passed conditions and returns the Query. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt usin
2 min read
Mongoose | replaceOne() Function
The replaceOne() function is same as update() function except MongoDB replace the existing document with the given document (no atomic operators like $set). Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, yo
2 min read
Mongoose | remove() Function
The remove() function is used to remove the documents from the database according to the condition. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using
2 min read
Mongoose | update() Function
The update() function is used to update one document in the database without returning it. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the comm
2 min read
Mongoose | estimatedDocumentCount() Function
The estimatedDocumentCount() function is quick as it estimates the number of documents in the MongoDB collection. It is used for large collections because this function uses collection metadata rather than scanning the entire collection. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package
2 min read
Mongoose Query.prototype.gt() API
The Mongoose Query API gt() method is used to scan all the documents in a collection and return those whose path values are greater than that passed in the method's argument. Syntax: Query.prototype.gt( path, val ) Parameters: It accepts the following parameters as mentioned above and described below: path: It is a string that identifies the attrib
3 min read
Mongoose count() Function
The Query.prototype.count() function is used to count the number of documents in a collection. This functions basically specifies this query as a count query. Syntax: Query.prototype.count() Parameters: This function accepts one array parameter i.e. callback function. Return Value: This function returns Query Object. Installation of mongoose module
2 min read
Mongoose Query() Function
The Query constructor is used for building the queries. So the user does not need to instantiate a Query directly. The `query` is an instance of `Query`. Syntax: Query() Parameters: This function has optional parameters like model, condition, collection and options. Return Value: This function returns Query object. Installation of mongoose module:
2 min read