I'm making a Mern project and I need to update two fields in a mongo db record.
I have two fields, one is an array of objects called wallets and the other is transactions.
I get an object from the frontend that includes the amount, index of the wallet where the transaction was made, because wallets are arrays of objects in mongo.
Now I need to subtract the transaction amount from the wallet. How to do this I have written a controller in node.js but it is not doing anything.
The object I receive from the 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 database records--
{"_id":{"$oid":"64a5a396ec152ab4f5e1c60c"}, "firstName":"Vinayak", "lastName":"Pandey", "email":"abc@123.com", "password":"b$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O", "Wallets":[{"name":"paytm","amount":500}, {"name":"hdfc","amount":5000}, {"name":"test","amount":3020}]
Suppose I made a transaction of 50 rupees from namde paytm wallet, so what I want is The amount in the object with name paytm should be reduced by rs-50 so initially it is After processing, rs500 should become rs450....
To apply the
In embedded documents or arrays,
$inc code>
operator at the element of the array. We should use dot notation to specifyLocation $
mongoplayground
enter:
Output:
renew
Update an array element using a specific array index: