node.js - 如何在快递中更新用户的个人资料?
问题描述
我想更新一个特定用户的财务记录,它是一个数组。
<-- 这是我的用户模型 -->
const FinanceSchema = new mongoose.Schema({
moneyToBePaid: {
type: Number,
},
moneyPaid: {
type: Number,
},
moneyToBeReceived: {
type: Number,
},
moneyReceived: {
type: Number,
},
});
const UserSchema = new mongoose.Schema({
financialInformation: [FinanceSchema],
});
module.exports = mongoose.model("user", UserSchema);
<-- 这是我的发帖路线-->
router.post("/users/:id/profile", async (req, res) => {
const _id = req.params.id;
const {
moneyToBePaid,
moneyPaid,
moneyToBeReceived,
moneyReceived,
} = req.body;
const finance = {
moneyToBePaid,
moneyPaid,
moneyToBeReceived,
moneyReceived,
};
try {
const user = await User.findById(_id);
user.financialInformation.push(finance);
await user.save();
res.status(200).json(user);
}
<-- 这是我的更新路线-->
router.patch("/users/:user_id/profile/:profile_id", async (req, res) => {
const user_id=req.params.user_id;
const profile_id=req.params.profile_id;
try {
}
我很困惑如何更新特定用户的特定财务记录。
解决方案
假设您要更新特定财务数组元素的 moneyPaid 属性:
try {
const user_id=req.params.user_id;
const profile_id=req.params.profile_id;
await User.findOneAndUpdate(
{ "_id": user_id, "financialInformation._id": profile_id },
{
"$set": {
"financialInformation.$.moneyPaid": "2258" // the data you want to update
}
});
res.status(200).send('user updated');
} catch(err) {
console.log(err);
res.send(err);
}
推荐阅读
- java - 带有bom的maven多项目结构
- python - 在新函数中使用函数的结果(加上更多)
- php - 如何使用复选框中的多个值构建 WHERE 条件?
- sql - SQL如何用每个月的数量计算每个项目?
- javascript - 为什么 Edge 浏览器不像其他浏览器那样处理 Javascript setTimer()
- docker - 如何增加卷 var/lib/docker/overlay2 的大小或安装到 Debian VM 中的新虚拟磁盘
- firebase - FutureBuilder 小部件仅使用 Firebase RealtimeDatabase 返回“DataSnapshot”实例
- angular - 制作一个角度全局解析器以使数据在每条路线中都可用
- email - 按术语 oa 产品属性自定义电子邮件
- r - R中的配对t检验给了我这个错误:没有足够的'x'观察