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....
P粉7970046442023-09-14 13:59:00
To apply the $inc code>
operator at the element of the array. We should use dot notation to specify
In embedded documents or arrays,
db.collection.update({ email: "abc@123.com", "Wallets.name": "paytm" }, { "$inc": { "Wallets.$.amount": -50 } })
enter:
[ { "_id": "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 } ] } ]
Output:
[ { "Wallets": [ { "amount": 450, "name": "paytm" }, { "amount": 5000, "name": "hdfc" }, { "amount": 3020, "name": "test" } ], "_id": "64a5a396ec152ab4f5e1c60c", "email": "abc@123.com", "firstName": "Vinayak", "lastName": "Pandey", "password": "b$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O" } ]
renew
Update an array element using a specific array index:
const idx = 1; db.users.updateOne( { email: 'abc@123.com' }, { $inc: { [`Wallets.${idx}.amount`]: -50, }, }, );