尝试使用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。

最佳答案

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

09-25 19:15