【问题标题】:Mongoose - findByIdAndUpdate and req.body deleting key valuesMongoose - findByIdAndUpdate 和 req.body 删除键值
【发布时间】:2020-05-08 02:16:59
【问题描述】:

我有一个包含很多键/值的模型,以及用于更新模型的 PUT 路由。我希望能够将req.body 发送到猫鼬方法findByIdAndUpdate

例如,这里是模型的一部分。

"generalInfo": {
    "tailNum": 1231231231231,
    "model": "sd9ia0da",
    "maxGasFuel": 1286123,
    "wingSurfaceArea": 123,
    "thrust": 123123,
    "takeOffSpeed": 123,
    "coeficientOfLift": 12334
}

当我发送更新tailNum 值的请求时,它会删除generalInfo 对象中的所有其他内容,只留下tailNum 键/值。

这是我的 PUT 请求代码。

// * @route   PUT /api/aircraft/:id
// ? @desc    Update an aircraft by ID
// ! @access  Private
router.put("/:id", auth, async (req, res) => {
  try {
    const dbAircraft = await Aircraft.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );

    res.json(dbAircraft);
  } catch (err) {
    console.log(err);
    res.status(500).send(`Server error`);
  }
});

我知道我可以手动解构req.body 的值并将它们发送到自定义对象中,但是这个模型的值太多以至于不可行。

【问题讨论】:

  • 您能否也提及 Mongoose 模式的代码?
  • 我无法重现该问题。您如何确认数据已被删除?
  • @AravindaMeewalaarachchi 绝对。这是模型的粘贴箱。 pastebin.com/3sxt5Nvy@KashinathPatekar 我通过直接查看文档与 mLab 进行了验证。不幸的是,以下解决方案($set,传播运算符)均无效。
  • 我检查了您的架构...我在其中找不到任何问题...您能否也提及您的验证文件??
  • @AravindaMeewalaarachchi 不幸的是相同的输出。会不会是 Mongoose 的版本问题?我不知道。这是回购:github.com/graysonlee123/kelby-manifest

标签: javascript node.js express mongoose


【解决方案1】:

一个选项可能是将 req.body 作为这样的对象发送:

router.put("/:id", auth, async (req, res) => {
  try {
    let update = req.body;
    const dbAircraft = await Aircraft.findByIdAndUpdate(
      {req.params.id,
       update,
      { new: true, runValidators: true }
    );

    res.json(dbAircraft);
  } catch (err) {
    console.log(err);
    res.status(500).send(`Server error`);
  }
});

//OR
router.put("/:id", auth, async (req, res) => {
  try {
    const dbAircraft = await Aircraft.findByIdAndUpdate(
      req.params.id,
      {req.body},
      { new: true, runValidators: true }
    );

    res.json(dbAircraft);
  } catch (err) {
    console.log(err);
    res.status(500).send(`Server error`);
  }
});

【讨论】:

    【解决方案2】:

    您的实现似乎不正确。使用

    router.put("/:id", auth, async (req, res) => {
      try {
        const dbAircraft = await Aircraft.findByIdAndUpdate(
          req.params.id,
          {$set: req.body},
          { new: true, runValidators: true }
        );
    
        res.json(dbAircraft);
      } catch (err) {
        console.log(err);
        res.status(500).send(`Server error`);
      }
    });
    

    【讨论】:

    • 欢迎来到 SO,如果您解释您的解决方案而不是仅仅粘贴一些代码,将会更有帮助。提供更多上下文不仅可以帮助提出问题的用户,还可以帮助之后到达这里的每个人。
    【解决方案3】:
    router.put("/:id", auth, async (req, res) => {
      try {
        const dbAircraft = await Aircraft.findByIdAndUpdate(
          req.params.id,                     // «Object|Number|String» value of _id to query by
          { ...req.body },                   // «Object»
          { new: true, runValidators: true } // «Object» optional see https://mongoosejs.com/docs/api.html#query_Query-setOptions
        );
      // Example: Model.findByIdAndUpdate(123456, { name: 'my name' }, { new: true, runValidators: true })
      // Example: Model.findByIdAndUpdate({ _id: 123456 }, { name: 'my name' }, { new: true, runValidators: true })
    
        res.json(dbAircraft);
      } catch (err) {
        console.log(err);
        res.status(500).send(`Server error`);
      }
    });
    

    【讨论】:

    • 欢迎来到 SO,如果您解释您的解决方案而不是仅仅粘贴一些代码,将会更有帮助。提供更多上下文不仅可以帮助提出问题的用户,还可以帮助之后到达这里的每个人。
    • @AlvinSator 感谢您的建议。我应该为此添加描述性材料吗?
    • 对您的解决方案试图实现的目标或为什么要采用这种方式进行一些解释就足够了。
    猜你喜欢
    • 2015-01-22
    • 2015-07-10
    • 1970-01-01
    • 2021-05-26
    • 2021-10-23
    • 2012-12-14
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多