Search code examples
node.jsreactjsmongodbmongoosemongodb-query

Update transactional value in mongodb


i am making a mern project wehre i need to update two fields in mongo db record .

i have two fields one is array of object named as Wallets and another is transaction.

i am getting a object from frontend which include the amount,index of wallet from which the transaction is made as wallets is array of object in mongo.

now i need to subtract the amount of transaction from the wallet. how to do it i have written a controller in node.js but its not doing anything.

my object that i receive from front end if..

transaction = { amount: '50', wallet: 0, type: 'expense', description: 'kmop' };

my node js controller is...

module.exports.addTransaction = async (req, res) => {
  const transaction = req.body;
  const {wallet} = transaction;

  try {
      const walletName = `Wallets.${wallet}.amount`
      await UserModel.findOneAndUpdate(
        { email: email },
        {  $inc: { walletName : -transaction.amount}   ,
          $push: { transactions: { $each: [transaction], $position: 0 } } }
      );
      res.send({stat: true});
    } 
    else {
      console.log(data)
      res.send({ stat: false });
    }
  } catch (err) {
    console.log("err",err)
    res.send({ stat: false, err: err.message });
  }
};

my mongo db record--

{"_id":{"$oid":"64a5a396ec152ab4f5e1c60c"},
"firstName":"Vinayak",
"lastName":"Pandey",
"email":"[email protected]",
"password":"$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O",
"Wallets":[{"name":"paytm","amount":500},
           {"name":"hdfc","amount":5000},
           {"name":"test","amount":3020}]

Suppose i made a transaction from wallet namde paytm of rs 50 so i want that is the amount in object with name as paytm should be decreased by rs-50 so initially it was rs500 after the process it should became rs450....


Solution

  • To apply $inc operator at an element of an array. We should use dot notation to specify a <field> in an embedded document or in an array,

    The positional $

    The $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

    db.collection.update({
      email: "[email protected]",
      "Wallets.name": "paytm"
    },
    {
      "$inc": {
        "Wallets.$.amount": -50
      }
    })
    

    mongoplayground

    Input:

    [
      {
        "_id": "64a5a396ec152ab4f5e1c60c",
        "firstName": "Vinayak",
        "lastName": "Pandey",
        "email": "[email protected]",
        "password": "$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O",
        "Wallets": [
          {
            "name": "paytm",
            "amount": 500
          },
          {
            "name": "hdfc",
            "amount": 5000
          },
          {
            "name": "test",
            "amount": 3020
          }
        ]
      }
    ]
    

    Output:

    [
      {
        "Wallets": [
          {
            "amount": 450,
            "name": "paytm"
          },
          {
            "amount": 5000,
            "name": "hdfc"
          },
          {
            "amount": 3020,
            "name": "test"
          }
        ],
        "_id": "64a5a396ec152ab4f5e1c60c",
        "email": "[email protected]",
        "firstName": "Vinayak",
        "lastName": "Pandey",
        "password": "$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O"
      }
    ]
    

    UPDATE

    Update an element of array with a specific array index:

    const idx = 1;
    db.users.updateOne(
        {
            email: '[email protected]'
        },
        {
            $inc: {
                [`Wallets.${idx}.amount`]: -50,
            },
        },
    );