【问题标题】:How to use mongoose findAndUpdateOne()如何使用猫鼬 findAndUpdateOne()
【发布时间】:2021-01-02 03:21:27
【问题描述】:

我正在尝试使用 findOneAndUpdate() 方法通过 mongoose 更新 mongoDB, 我从 req.body 中解构了我的字段,但是如果我只更新了一个值,其他人设置为 null,我该如何解决这个问题


代码

  const { name, email, phone, type } = req.body;

  await Contact.findOneAndUpdate(
    { _id: req.params.id },
    { $set: { name, email, type, phone } },
    { upsert: true },
    (err, updatedContact) => {
      if (err) {
        console.error(err.message);
        res.status(400).send('Could not updat');
      } else {
        res.json(updatedContact);
      }
    }
  );
  
});
******************************************

【问题讨论】:

  • 你能澄清你在问什么吗?
  • 如何在不将不想更新的值设置为 null 的情况下使用 findOneandUpdate
  • 已经找到解决方案,感谢您的努力

标签: node.js mongodb mongoose mern


【解决方案1】:

这给了我我期望的理想结果,请不要说我没有实施错误检查,你可以使用“express-validator”来做到这一点

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  const { name, email, phone, type } = req.body;
  // Build contact object
  const updatedContact = {};
  if (name) updatedContact.name = name;
  if (email) updatedContact.email = email;
  if (phone) updatedContact.phone = phone;
  if (type) updatedContact.type = type;

  try {
    await Contact.findOneAndUpdate(
      { _id: req.params.id },
      { $set: updatedContact },
      { new: true }
    );

    res.json(updatedContact);
  } catch (err) {
    console.error(err.message);
    res.status(400).send('Could not update');
  }
});

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 1970-01-01
    • 2012-02-19
    • 2017-10-11
    • 2013-07-27
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多