Transaction
TheTransaction 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 usingdb.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 backcommit()
Commits the transaction, making all changes permanent.
rollback()
Rolls back the transaction, discarding all changes.
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 documentfindById()
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 otherwiseupdateById()
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
deleteById()
Deletes a document by its ID.
string
required
Name of the collection
string
required
Document ID to delete
findAll()
Retrieves all documents from a collection.
string
required
Name of the collection
T[]
Array of all documents in the collection
count()
Counts all documents in a collection.
string
required
Name of the collection
number
Number of documents in the collection
Collection management
createCollection()
Creates a new collection.
string
required
Name of the collection to create
dropCollection()
Deletes a collection and all its documents.
string
required
Name of the collection to drop
renameCollection()
Renames a collection.
string
required
Current name of the collection
string
required
New name for the collection