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.



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