首页 > 解决方案 > 如何在快递中更新用户的个人资料?

问题描述

我想更新一个特定用户的财务记录,它是一个数组。

<-- 这是我的用户模型 -->

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 {
    
    
  } 

我很困惑如何更新特定用户的特定财务记录。

标签: node.jsexpressmongoose

解决方案


假设您要更新特定财务数组元素的 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);
}

推荐阅读