0 points

Handling mongoose validation error messages - Stack Overflow


dashboard

Sat Oct 10 2020 17:41:42 GMT+0000 (UTC)

Posted by @mishka #javascript #nodejs #mongoose

router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
content_copy Copy

https://stackoverflow.com/questions/61056021/improve-mongoose-validation-error-handling