Diddy
Diddy

Reputation: 31

How do i update in MongoDB with Node.JS

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..

Upvotes: 3

Views: 63

Answers (1)

lpizzinidev
lpizzinidev

Reputation: 13289

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 });
  }
});

Upvotes: 1

Related Questions