3

i have this code i am trying to write, the code is supposed to update the balance in MongoDB after properly computing the balance. The challenge is , it does not, it properly computes the balance, but updating the column for the user, it does not update. Looking out to see where and how to update the balances only I have not seen anything to help.

My code is Looking thus :

const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");


router.post("/update-balance/:email", async (req, res) => {

    try {
        if (
          !req.headers.authorization ||
          !req.headers.authorization.startsWith("Bearer ") ||
          !req.headers.authorization.split(" ")[1]
        ) {
          return res.status(422).json({ message: "Please Provide Token!" });
        }

        const amount = parseInt(req.body.amount);

        const user = await User.find({ email: req.params.email });
        const balance = parseInt(user[0].balance);

        //return balance;
        //console.log(balance);

        const total_amt = amount + balance;
        //console.log(total_amt);

        // update Balance
        const wallet_user = new User();
        try{
          await wallet_user.updateOne({email : req.params.email}, {$set: {balance: total_amt}});
        }catch(err){
          console.log(err);
        }

        return res.send({ error: false, message: "OK" });

      } catch (error) {
        res.status(404).json({ message: error.message });
      }

});



module.exports = router;

What Am I suppose to do that i am not doing rightly, kindly help.

The code above shows What I have attempted..

1 Answer 1

1

You can use $inc:

router.post('/update-balance/:email', async (req, res) => {
  try {
    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith('Bearer ') ||
      !req.headers.authorization.split(' ')[1]
    ) {
      return res.status(422).json({ message: 'Please Provide Token!' });
    }

    const amount = parseInt(req.body.amount);

    try {
      await User.findOneAndUpdate(
        { email: req.params.email },
        { $inc: { balance: amount } }
      );
    } catch (err) {
      console.log(err);
    }

    return res.send({ error: false, message: 'OK' });
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

$inc does not add, just doubles the numbers somehow. like in the wallet, the user has $50, then he pays in another 7000, he should get 7050, instead he gets 7660. Dont know why it behaves so
$set worked! using almost the same code with the $set parameter worked. everything else is good. Once again, thanks
@Diddy That does not make sense as $set updates whatever value you pass it with and does not add as desired i.e if the current balance is 50 and you update with { $set: { balance: 7000 } } then the new balance would be 7000. $inc on the other hand updates the balance by adding whatever value to the current one i.e. update with { $inc: { balance: 7000 } } then the new balance would be 7050, like what the OP suggested in their solution above
@chridam if u look at what i did, i have done the computation already, what i needed to do was to set the computed into the database. Then i followed somethings in his code and got it to work as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.