Skip to main content

Transaction

The Transaction class provides ACID-compliant transaction support for performing multiple database operations atomically. Transactions ensure data consistency and allow you to roll back changes if an error occurs.

Creating a transaction

Transactions are created using db.beginTransaction():

Transaction lifecycle

isActive()

Checks if the transaction is still active and can be used.
boolean
true if transaction is active, false if committed or rolled back
Example

commit()

Commits the transaction, making all changes permanent.
Example

rollback()

Rolls back the transaction, discarding all changes.
Example

CRUD operations

All CRUD operations in transactions are type-safe when you use TypeScript generics.

insert()

Inserts a document into a collection.
string
required
Name of the collection
Omit<T, '_id'>
required
Document to insert (without _id field, which will be auto-generated)
string
The auto-generated _id of the inserted document
Example

findById()

Finds a document by its ID.
string
required
Name of the collection
string
required
Document ID to find
T | null
The document if found, null otherwise
Example

updateById()

Updates a document by its ID.
string
required
Name of the collection
string
required
Document ID to update
Partial<T>
required
Partial document with fields to update
Example

deleteById()

Deletes a document by its ID.
string
required
Name of the collection
string
required
Document ID to delete
Example

findAll()

Retrieves all documents from a collection.
string
required
Name of the collection
T[]
Array of all documents in the collection
Example

count()

Counts all documents in a collection.
string
required
Name of the collection
number
Number of documents in the collection
Example

Collection management

createCollection()

Creates a new collection.
string
required
Name of the collection to create
Example

dropCollection()

Deletes a collection and all its documents.
string
required
Name of the collection to drop
Example

renameCollection()

Renames a collection.
string
required
Current name of the collection
string
required
New name for the collection
Example

Advanced transaction patterns

Multi-collection atomic operations

Transactions can span multiple collections, ensuring atomicity across all operations:

Conditional updates

You can perform read-modify-write operations safely within a transaction:

Data migration

Transactions are ideal for data migrations:

Transaction retry configuration

Transactions automatically retry on conflicts. Configure retry behavior using database-level settings:

Best practices

Keep transactions short

Transactions hold locks, so keep them as short as possible:

Always handle errors

Always use try-catch and rollback on errors:

Don’t reuse transactions

Create a new transaction for each atomic operation: