Convert balance between two budgets

Hello everyone. I’m currently learning Express and MongoDB using Mongoose in my apps.

I have a case in that I want to convert a balance from one budget to another one

I did it in this essential way:

const convertBalance = async (req, res) => {
    //Get the amount that I want to convert, and the budget that I want to convert to
    const { balanceToConvert, convertTo } = req.body
    if (!balanceToConvert || !convertTo) {
        throw new BadRequest("Please provide amount and budget to convert")
    }

    // current budget is the budget I want to convert from
    const currentBudgetId = req.params.id

    const currentBudget = await Budget.findOne({
        _id: req.params.id,
        createdBy: req.user.userId
    })

    if (!currentBudget) {
        throw new NotFound("current budget not found, please select a valid and active budget")
    }

   // get the budget that I want to convert to
    const convertToBudget = await Budget.findOne({
        _id: convertTo,
        createdBy: req.user.userId
    })

    if (!convertToBudget) {
        throw new NotFound("The budget you wanted to convert to not found, please select a valid and active budget")
    }

   // cut the amount from the budget
    await Budget.findOneAndUpdate({
        _id: req.params.id,
        createdBy: req.user.userId
    },
    {
        balance: currentBudget.balance - balanceToConvert
    },
    {
        new: true,
        runValidators: true
    })

   // added that amount to the other budget
    await Budget.findOneAndUpdate(
        {
            _id: convertTo,
            createdBy: req.user.userId
        }, 
        {
            balance: convertToBudget.balance + balanceToConvert
        },
        {
            new: true,
            runValidators: true
        }
    )
    
    res.status(StatusCodes.OK).json({ success: true, data: "amount converted successfully"})
}

My question is:

  • is there a better way to switch and calculate values between my documents in MongoDB or Mongoose than the way I went for? I feel my code is more complicated

Thanks

At the very least you should put the two updates in a transaction.

You could do this with a $merge back into the Budget collection, but be wary of trying to do everything in one call that renders the code a pain to work with or someone else to maintain.
You could also do it in one bulk operation, adding multiple updates to one bulk object and sending that to the server: