javascript - Mongoose 使用数组的另一个字段的项目更新字段
问题描述
我正在构建一个费用跟踪器应用程序,有一个用户集合,其中包含名称、金额、费用数组、收入数组等字段。
我的数据库是 Mongo Db 和 Mongoose,服务器是用 Express 编写的。
我正在尝试实现用户可以删除费用的路线,在删除费用后我想更新余额并使余额 = 余额 + 费用。我可以删除和支出但无法更新余额,因为我不知道如何从已删除的支出中检索余额
这是删除路线:
router.delete("/", (req, res) => {
const { UserID, ExpenseID } = req.query;
const query = {
$pull: {
Expenses: { _id: ExpenseID },
},
};
User.findByIdAndUpdate(UserID, query)
});
我想添加一个 Mongoose 方法,该方法将从收到的费用 Id 中获取费用金额并将其存储在一个变量中,在费用被删除后,我想调用一个方法来更新 Promise 中用户的余额。
这是我打算做的一个例子
// Deletes An Expense
router.delete("/", (req, res) => {
const { UserID, ExpenseID } = req.query;
const query = {
$pull: {
Expenses: { _id: ExpenseID },
},
};
User.find({/*Some Query Which Will Return me The Provided Expense ID's Amount*/})
User.findByIdAndUpdate(UserID, query)
.then(() => {
// Once I find and Remove the Expense, Now I would Like to Update the Users Balance
// NewBalance = OldBalance + Expense ID's Amount Returned by the Find Method
// Here I would Call another User.find method to update the Users Balance
})
});
假设从上面的数据库快照中,我想删除费用(从 0 开始)第一个对象元素,名称:Uber Fare,我将向服务器发送为 6091f725403c2e1b8c18dda3 的对象 ID,并且应该期望我的余额从 48495 增加到49695
解决方案
What you can do is:
- Fetch user document with
UserID
- Find the expense with
ExpenseID
- Update the
Balance
with the expense amount - Remove expense from
Expenses
array - Save user document
router.put("/", async (req, res) => {
try {
const { UserID, ExpenseID } = req.query;
let user = await User.find({ _id: UserID });
index = user.Expenses.findIndex((expense) => expense._id === ExpenseID);
if (index != -1) {
user.Balance += user.Expenses[index].Amount;
user.Expenses.splice(index, 1);
}
await user.save();
return res.status(200).json({ success: true, user: user });
} catch (error) {
return res.status(400).json({ success: false, error: error })
}
});
NOTE: Since this is updating the document, I configured put
method instead of delete
on the router.
推荐阅读
- javascript - 如何按顺序遍历 ES6 Map?
- docker - 无法使用 docker 连接到我的 prestashop 数据库
- javascript - JavaScript:在一天开始时更新一次本地存储
- python - 如果其中一个字典被更新,Python 连接的字典列表会修改列表中的所有字典实例
- python - 如何在同一个脚本中重复使用一段代码,而不是每次都重新输入?
- javascript - React 中对象的访问值
- flutter - 如何显示未来
图片? - c++ - std::filesystem::path 没有 operator+?
- javascript - 自动滚动到先前选择的特定行 asp.net core
- javascript - 如何使用 javascript 将 dateTime 转换为正确的 ISO 字符串