'MongoError: Cannot call abortTransaction twice; MongoError: Cannot call abortTransaction after calling commitTransaction

When I run the send route I have error: MongoError: Cannot call abortTransaction twice and MongoError: Cannot call abortTransaction after calling commitTransaction.

I have two collections car and color. And in the same time I want to add to arrays: car.colors.push(model); color.brands.push(year); and save in database. But I want use withTransaction and session from mongoose. I don't want the situation that due to error, car.colors.push(model); will be saved in database, but color.brands.push(year); won't be saved.

module.exports.send = async (req, res) => {

    const sess = await mongoose.startSession();
  

    if(role === 'car') {
        try {

            await sess.withTransaction(async () => {
                const car = await Cars.findOne({ _id: sender});
                const color = await Colors.findOne({_id: keeper});
    

                let model =  {
                    contentInfo : {
                        msg : msg
                    }
                };

                let year =  {
                    contentInfo : {
                        msg : msg
                    }
                }
        
        
                car.colors.push(model);
                color.brands.push(year);
                
                await car.save({session: sess});
                await color.save({session: sess});
        
                await sess.commitTransaction();

                sess.endSession();

                return res.json(car);
            });

        } catch (error) {
       
            await sess.abortTransaction();
            sess.endSession();

            throw error; 
        }      
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source