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