我该如何解决findOneAndUpdate遇到的这个问题

时间:2019-10-22 07:31:01

标签: javascript mongodb express mongoose updates

尝试使用findOneAndUpdate方法更新mongodb文档

尝试以各种方式查找文档并以不同的方式重新建立更新

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");
    }
  }
);

我希望它返回更新的用户,但是我一直捕获错误并返回500。

1 个答案:

答案 0 :(得分:3)

bcrypt.genSalt和哈希方法返回promise,因此您需要等待。

我也将findOneAndUpdate更改为findByIdAndUpdate,我认为在这种情况下更清楚。

您可以尝试使用此代码吗?

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");
    }
  }
);