【问题标题】:How to update subdocument?如何更新子文档?
【发布时间】:2020-10-21 16:10:27
【问题描述】:

我想更新子文档 FinanceSchema。这是我的模型

            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.unshift(finance);
            await user.save();
        }

我无法更新financeInformation(FinanceSchema)。我很困惑如何定义和更新路线。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    尝试致电markModified(),因为猫鼬可能不会自动获取更改:

    const user = await User.findById(_id);
    user.financialInformation.unshift(finance);
    user.markModified('financialInformation');
    await user.save();
    

    编辑:

    如果你想在某个索引处修改financialInformation,你可以简单地执行以下操作:

    const user = await User.findById(_id);
    user.financialInformation[0].moneyReceived = 1000000;
    await user.save();
    

    【讨论】:

    • 我能够在用户模式中推送金融信息。我唯一的问题是我无法更新特定的金融信息,它是一个数组。
    • 你的意思是你想在某个索引处更新financialInformation?还是所有数组元素?
    • 查看我的编辑。我在索引0 上修改moneyReceived 的值。
    • 如果这解决了您的问题,请确保点击左侧的复选标记接受此答案。
    • 其实都是。一个用户有 3 个财务信息。我应该能够更新所有 3 个或其中一个。
    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2016-11-04
    • 2019-02-26
    • 2016-06-17
    • 2015-05-14
    • 2015-04-12
    相关资源
    最近更新 更多