簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z 使用另一個字段即數組的項目更新字段

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

我正在構建一個費用跟蹤器應用程序,有一個用戶集合,其中包含名稱、金額、費用數組、收入數組等字段。

我的數據庫是帶有 Mongoose 的 Mongo Db,服務器是用 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
  })
});

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

你可以做的是:

  1. 使用UserID獲取用戶文檔
  2. 使用ExpenseID查找費用
  3. 使用費用金額更新Balance
  4. Expenses數組中刪除費用
  5. 保存用戶文檔
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 })
  }
});

注意:由於這是更新文檔,我在路由器上配置put方法而不是delete

像這樣為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)
      }
  });
};

在您的路由處理程序中訪問它

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

static methodremove費用並update余額。 說明: static method只是找到用戶並遍歷他們的Expenses並刪除所需的expense ,然后將amount添加到balance中。 最后user.save()方法來保存所有文檔。

注意:僅當您確定費用 ID 存在於 Expense 數組中時才使用此選項,否則您只需在 static 方法中添加額外的檢查

還將 static 方法放在創建schema的文件中,並將model放在它們的兩個創建之間,即在創建 userSchema 之后和將其最終確定為model之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM