MongoDB session for the transaction (pass this to all MongoDB operations)
The database instance passed during consumer creation
The MongoDB client instance passed during consumer creation
Promise that resolves when all operations in the callback complete
Medicine assignment with event
await outbox.publish(
{
type: 'MedicineAssigned',
patientId: 'patient-123',
medicineId: 'med-456'
},
async (session, db) => {
// Store assignment in same transaction
await db.collection('medicine_assignments').insertOne({
patientId: 'patient-123',
medicineId: 'med-456',
assignedAt: new Date(),
assignedBy: 'doctor-789'
}, { session })
// Update patient record
await db.collection('patients').updateOne(
{ _id: 'patient-123' },
{ $push: { assignedMedicines: 'med-456' } },
{ session }
)
}
)
Order creation with multiple updates
await outbox.publish(
{
type: 'OrderCreated',
orderId: 'order-123',
customerId: 'customer-456'
},
async (session, db, client) => {
// Create order
await db.collection('orders').insertOne(order, { session })
// Update customer stats
await db.collection('customers').updateOne(
{ _id: 'customer-456' },
{ $inc: { totalOrders: 1 } },
{ session }
)
// Access different database if needed
const analyticsDb = client.db('analytics')
await analyticsDb.collection('events').insertOne(
{ type: 'order_created', timestamp: new Date() },
{ session }
)
}
)
Publish - Function type that accepts this callback
Callback function type for publishing events with business logic in the same transaction.
This callback receives a new MongoDB session and allows you to perform business operations atomically with event publishing. The callback runs inside a MongoDB transaction, ensuring either both operations succeed or both fail.