首页 > 解决方案 > Mongoose 使用数组的另一个字段的项目更新字段

问题描述

我正在构建一个费用跟踪器应用程序,有一个用户集合,其中包含名称、金额、费用数组、收入数组等字段。

我的数据库是 Mongo Db 和 Mongoose,服务器是用 Express 编写的。

这是填充值后的数据库截图 MongoDB 数据库截图

我正在尝试实现用户可以删除费用的路线,在删除费用后我想更新余额并使余额 = 余额 + 费用。我可以删除和支出但无法更新余额,因为我不知道如何从已删除的支出中检索余额


这是删除路线:

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

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


What you can do is:

  1. Fetch user document with UserID
  2. Find the expense with ExpenseID
  3. Update the Balance with the expense amount
  4. Remove expense from Expenses array
  5. 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.


推荐阅读