简体   繁体   English

如何解决我在使用 findOneAndUpdate 时遇到的这个问题

[英]how do I fix this problem I'm having with findOneAndUpdate

Trying to update mongodb doc using findOneAndUpdate method尝试使用findOneAndUpdate方法更新 mongodb 文档

tried looking up the doc in various ways and reformating the update in different ways尝试以各种方式查找文档并以不同方式重新格式化更新

router.put(
  "/edit",
  [
    auth,
    [
      check("name", "Name is required")
        .not()
        .isEmpty(),
      check("email", "Please enter a valid email").isEmail(),
      check(
        "password",
        "Please enter a password with 8 or more characters"
      ).isLength({ min: 8 })
    ]
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(404).json({ errors: errors.array() });
    }

    const { email, password, name } = req.body;

    const update = {
      email,
      password,
      name
     };

    const salt = bcrypt.genSalt(10);

    update.password = bcrypt.hash(password, salt);

    try {
      const user = await User.findOneAndUpdate(
        { user: req.user.id },
        { $set: update },
        { new: true, upsert: true }
      );
      res.json(user);
    } catch (err) {
      console.error(err);
      res.status(500).send("Server Error");
    }
  }
);

I want it to return the updated user but I keep catching an error and return 500.我希望它返回更新后的用户,但我不断发现错误并返回 500。

bcrypt.genSalt and hash methods return promise, so you need to await. bcrypt.genSalt 和 hash 方法返回 promise,所以需要等待。

Also I changed to findOneAndUpdate to findByIdAndUpdate which I think is clearer in this case.此外,我将 findOneAndUpdate 更改为 findByIdAndUpdate,我认为在这种情况下更清楚。

Can you try with this code?您可以尝试使用此代码吗?

router.put(
  "/edit",
  [
    auth,
    [
      check("name", "Name is required")
        .not()
        .isEmpty(),
      check("email", "Please enter a valid email").isEmail(),
      check(
        "password",
        "Please enter a password with 8 or more characters"
      ).isLength({ min: 8 })
    ]
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(404).json({ errors: errors.array() });
    }

    const { email, password, name } = req.body;

    const update = {
      email,
      password,
      name
    };

    const salt = await bcrypt.genSalt(10);

    update.password = await bcrypt.hash(password, salt);

    try {
      const user = await User.findByIdAndUpdate(req.user.id, update, {
        new: true,
        upsert: true
      });
      res.json(user);
    } catch (err) {
      console.error(err);
      res.status(500).send("Server Error");
    }
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM