简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z 使用另一个字段即数组的项目更新字段

[英]Mongoose Update Field With the Item of the Another Field That is Array

I am building an Expense Tracker Application, There is a User Collection that has fields like Name, Amount, Expenses Array, Incomes Array, and So On.我正在构建一个费用跟踪器应用程序,有一个用户集合,其中包含名称、金额、费用数组、收入数组等字段。

My Database Is Mongo Db with Mongoose and the Server Is Written In Express.我的数据库是带有 Mongoose 的 Mongo Db,服务器是用 Express 编写的。

Here Is A Screenshot Of the Database after The Values are Filled这是填充值后的数据库截图MongoDB 数据库截图

I am trying to Implement a Route in which The User Can Delete an Expense and After Deleting the Expense I want to update the Balance and make the Balance = Balance + Expense.我正在尝试实现用户可以删除费用的路线,在删除费用后我想更新余额并使余额 = 余额 + 费用。 I am able to Delete and Expense But Not able to Update the Balance as I do not know how to retrieve the Balance from the Deleted Expense我可以删除和支出但无法更新余额,因为我不知道如何从已删除的支出中检索余额


Here is the Delete Route:这是删除路线:

router.delete("/", (req, res) => {
  const { UserID, ExpenseID } = req.query;
  const query = {
    $pull: {
      Expenses: { _id: ExpenseID },
    },
  };
  User.findByIdAndUpdate(UserID, query)
  
});

I want to add a Mongoose Method which Will Fetch the Expense Amount from the Received Expense Id and Store it in a variable and After the Expense Gets Deleted, I want to call a method to update the balance of the User in the Promise.我想添加一个 Mongoose 方法,该方法将从收到的费用 ID 中获取费用金额并将其存储在一个变量中,在费用被删除后,我想调用一个方法来更新 Promise 中的用户余额。

Here is an example of what I intend to do这是我打算做的一个例子

// 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
  })
});

Let's Say From the Above Database Snap, I want to delete the Expenses (Starting From 0) 1st Object Element, Name: Uber Fare, I will send the Object Id which is 6091f725403c2e1b8c18dda3 to the Server and should Expect my Balance to Increase from 48495 to 49695 Let's Say From the Above Database Snap, I want to delete the Expenses (Starting From 0) 1st Object Element, Name: Uber Fare, I will send the Object Id which is 6091f725403c2e1b8c18dda3 to the Server and should Expect my Balance to Increase from 48495 to 49695

What you can do is:你可以做的是:

  1. Fetch user document with UserID使用UserID获取用户文档
  2. Find the expense with ExpenseID使用ExpenseID查找费用
  3. Update the Balance with the expense amount使用费用金额更新Balance
  4. Remove expense from Expenses arrayExpenses数组中删除费用
  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.注意:由于这是更新文档,我在路由器上配置put方法而不是delete

Create a static method for the schema like so像这样为schema创建一个static method

userSchema.statics.deleteExpenseUpdateBalance = async function (userID, expenseID) {
  const user = await this.findOne({ _id: userID });
  let userExpenses = user.Expenses;
  userExpenses.forEach((expense) => {
    if (expense._id === expenseID) {
      let amount = expense.Amount;
      let index = userExpenses.indexOf(expense);
      userExpenses.splice(index, 1);
      user.Balance += amount;
      return;
    }
  });

  user.save((err) => {
      if (err) {
          console.log(err)
      }
  });
};

Access this in your route handler在您的路由处理程序中访问它

router.delete("/", async (req, res) => {
  const { UserID, ExpenseID } = req.query;
  let result = await User.deleteExpenseUpdateBalance(UserID, ExpenseID)
});

This static method will remove the expense and update the balance.static methodremove费用并update余额。 Explanation: The static method just finds the user and iterates through their Expenses and removes the required expense and the amount is just added to the balance .说明: static method只是找到用户并遍历他们的Expenses并删除所需的expense ,然后将amount添加到balance中。 Finally the user.save() method is called to save all documents.最后user.save()方法来保存所有文档。

NOTE: Use this only if you are sure that the expenseID exists in the Expense array, otherwise you'll just have to add an extra check for that in the static method注意:仅当您确定费用 ID 存在于 Expense 数组中时才使用此选项,否则您只需在 static 方法中添加额外的检查

Also put the static method in the file where you create your schema and model in between both of their creations ie after you've created the userSchema and before you finalise it into a model .还将 static 方法放在创建schema的文件中,并将model放在它们的两个创建之间,即在创建 userSchema 之后和将其最终确定为model之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM