Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

balance is not getting updated after a transfer #9

Open
BHUPESH003 opened this issue Feb 1, 2024 · 2 comments
Open

balance is not getting updated after a transfer #9

BHUPESH003 opened this issue Feb 1, 2024 · 2 comments

Comments

@BHUPESH003
Copy link

if i am making a transfer from one account to another then the request successfully returns the "Transfer Successful" message but the balance in the Database is not getting updated.
PS:
i have already tried the promise.all and findByIdandUpdate and findOneandUpdate nothing changes.
Screenshot 2024-02-01 231249
Screenshot 2024-02-01 231317

@paras-verma7454
Copy link

Try this code

router.post("/transfer", authMiddleware, async (req, res) => {
    const session = await mongoose.startSession();

    session.startTransaction();
    const { amount, to } = req.body;

    // Fetch the accounts within the transaction
    const account = await Account.findOne({ userId: req.userId }).session(session);

    if (!account || account.balance < amount) {
        await session.abortTransaction();
        return res.status(400).json({
            message: "Insufficient balance"
        });
    }

    const toAccount = await Account.findOne({ userId: to }).session(session);

    if (!toAccount) {
        await session.abortTransaction();
        return res.status(400).json({
            message: "Invalid account"
        });
    }

    // Perform the transfer
    await Account.updateOne({ userId: req.userId }, { $inc: { balance: -amount } }).session(session);
    await Account.updateOne({ userId: to }, { $inc: { balance: amount } }).session(session);

    // Commit the transaction
    await session.commitTransaction();
    res.json({
        message: "Transfer successful"
    });
});

@yesahem
Copy link

yesahem commented Sep 21, 2024

if i am making a transfer from one account to another then the request successfully returns the "Transfer Successful" message but the balance in the Database is not getting updated. PS: i have already tried the promise.all and findByIdandUpdate and findOneandUpdate nothing changes. Screenshot 2024-02-01 231249 Screenshot 2024-02-01 231317

Github Link for the repo please

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants