我正在制作一个 Mern 项目,我需要更新 mongo db 记录中的两个字段。
我有两个字段,一个是名为钱包的对象数组,另一个是交易。
我从前端获取一个对象,其中包括进行交易的钱包的金额、索引,因为钱包是 mongo 中的对象数组。
现在我需要从钱包中减去交易金额。如何做到这一点我已经在node.js中编写了一个控制器,但它没有做任何事情。
我从前端收到的对象,如果..
transaction = { amount: '50', wallet: 0, type: 'expense', description: 'kmop' };
我的 Node js 控制器是...
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 });
}
};
我的 mongo 数据库记录--
{"_id":{"$oid":"64a5a396ec152ab4f5e1c60c"},
"firstName":"Vinayak",
"lastName":"Pandey",
"email":"abc@123.com",
"password":"$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O",
"Wallets":[{"name":"paytm","amount":500},
{"name":"hdfc","amount":5000},
{"name":"test","amount":3020}]
假设我从 namde paytm 钱包进行了一笔 50 卢比的交易,所以我想要的是 名称为 paytm 的对象中的金额应减少 rs-50,因此最初是 rs500经过处理后应该变成rs450....
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要应用
$inc code>运算符位于数组的元素处。我们应该使用 点符号 来指定在嵌入文档或数组中,位置 $
db.collection.update({ email: "abc@123.com", "Wallets.name": "paytm" }, { "$inc": { "Wallets.$.amount": -50 } })mongoplayground
输入:
[ { "_id": "64a5a396ec152ab4f5e1c60c", "firstName": "Vinayak", "lastName": "Pandey", "email": "abc@123.com", "password": "$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O", "Wallets": [ { "name": "paytm", "amount": 500 }, { "name": "hdfc", "amount": 5000 }, { "name": "test", "amount": 3020 } ] } ]输出:
[ { "Wallets": [ { "amount": 450, "name": "paytm" }, { "amount": 5000, "name": "hdfc" }, { "amount": 3020, "name": "test" } ], "_id": "64a5a396ec152ab4f5e1c60c", "email": "abc@123.com", "firstName": "Vinayak", "lastName": "Pandey", "password": "$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O" } ]更新
使用特定数组索引更新数组元素:
const idx = 1; db.users.updateOne( { email: 'abc@123.com' }, { $inc: { [`Wallets.${idx}.amount`]: -50, }, }, );