Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose return value from withTransaction callback

I want to utilize mongoose's withTransaction helper particularly for its ability to automatically retry transient transaction errors. However, it seems that the withTransaction helper is incapable of returning data, which is a problem for me.

I have code that looks like:

import { startSession } from 'mongoose';

async addItem(itemData) {
    const session = await startSession();
 
    session.startTransaction();
    try {
        const item = await new Item({ itemData }).save({ session });
        
        // a bunch of other async operations...

       await session.commitTransaction();
       session.endSession();

       return item;
    } catch (error) {
        await session.abortTransaction();
        session.endSession();
        throw error;
    }
}

How can I either (1) use the withTransaction helper but still have this function returning the item as it currently does, or (2) make this function automatically retry on transient transaction errors through some way other than using withTransaction.

like image 465
Infamous911 Avatar asked Aug 01 '26 05:08

Infamous911


1 Answers

This appears to be a known issue in the node driver. Some workarounds are provided in that ticket.

like image 75
D. SM Avatar answered Aug 02 '26 18:08

D. SM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!