Documentation / @andrew_l/mongo-transaction / withMongoTransaction
Function: withMongoTransaction() ​
Call Signature ​
withMongoTransaction<
T
,K
,Args
>(options
):WithMongoTransactionWrapped
<T
,K
,Args
>
Runs a provided callback within a transaction, retrying either the commitTransaction operation or entire transaction as needed (and when the error permits) to better ensure that the transaction can complete successfully.
Passes the session as the function's first argument or via useMongoSession()
hook
Type Parameters ​
T ​
T
K ​
K
= any
Args ​
Args
extends any
[] = any
[]
Parameters ​
options ​
WithMongoTransactionOptions
<T
, K
, Args
>
Returns ​
WithMongoTransactionWrapped
<T
, K
, Args
>
Example ​
const executeTransaction = withMongoTransaction({
connection: () => mongoose.connection.getClient(),
async fn() {
const session = useMongoSession();
const orders = mongoose.connection.collection('orders');
const { modifiedCount } = await orders.updateMany(
{ status: 'pending' },
{ $set: { status: 'confirmed' } },
{ session },
);
},
});
Call Signature ​
withMongoTransaction<
T
,K
,Args
>(connection
,fn
,options?
):WithMongoTransactionWrapped
<T
,K
,Args
>
Runs a provided callback within a transaction, retrying either the commitTransaction operation or entire transaction as needed (and when the error permits) to better ensure that the transaction can complete successfully.
Passes the session as the function's first argument or via useMongoSession()
hook
Type Parameters ​
T ​
T
K ​
K
= any
Args ​
Args
extends any
[] = any
[]
Parameters ​
connection ​
ConnectionValue
fn ​
Callback
<T
, K
, Args
>
options? ​
Omit
<WithMongoTransactionOptions
<any
, any
, any
[]>, "fn"
| "connection"
>
Returns ​
WithMongoTransactionWrapped
<T
, K
, Args
>
Example ​
const executeTransaction = withMongoTransaction(mongoose.connection.getClient(), async () => {
const session = useMongoSession();
const orders = mongoose.connection.collection('orders');
const { modifiedCount } = await orders.updateMany(
{ status: 'pending' },
{ $set: { status: 'confirmed' } },
{ session },
);
});