MongoDB’s Callback API runs transaction operations inside a callback and manages transaction startup, completion, aborts, and retries. It is the preferred alternative to the lower-level Core API for implementing multidocument transactions. section 8.4.1 section 8.4.3
A typical transaction follows these implementation steps:
- Start a logical session and associate every transaction operation with that session. section 8.4.1
- Define a callback containing the related reads and writes that must succeed or fail together. section 8.4.3
- Invoke the language driver’s callback helper, such as Node.js withTransaction, to start, commit, or abort the transaction. section 8.4.3
- Let the API retry transient transaction failures and uncertain commit results instead of implementing those mechanisms manually. section 8.4.1
Node.js transaction
Create a MongoClient, connect to MongoDB, start a session, and call session.withTransaction with an async callback. The callback can read account, customer, and transaction collections; the helper handles transaction completion and retries. Configure readConcern, writeConcern, and readPreference when the operation requires those settings. section 8.4.3
Table 8.1 Core API vs. Callback API
| Core API |
Callback API |
| Requires an explicit call to initiate and commit the transaction |
Initiates a transaction, performs the specified operations, and commits them or aborts if an error occurs |
| Does not automatically handle errors such as |
Automatically includes error-handling logic for |
| Requires explicitly passing a logical session to the API for each transaction |
Requires explicitly passing a logical session to the API for each transaction |
Compare the Callback API with the Core API for lifecycle control, error handling, and logical-session requirements. section 8.4.1
The convenience has an operational boundary: distributed transactions usually cost more than single-document writes. Prefer schema designs with embedded documents and arrays when they can keep related data together and avoid a transaction. section 8.4.3
