Get Mongoose validation error message in React

Viewed 816

I am trying to validate user creation/editing etc with Mongoose and get back the message on my front end, but all I get is

POST http://192.168.0.11:3000/users/create 400 (Bad Request)
CreateUser.jsx:48 Error: Request failed with status code 400
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.d.onreadystatechange (xhr.js:61)

My User schema:

const User = new mongoose.Schema({
  Name: {
    type: String,
    required: "Username is required for a user!",
    minlength: 4,
    maxlength: 16,
  },
  Password: {
    type: String,
    required: "Password is required for a user!",
    minlength: 4,
    maxlength: 20,
  },
  Role: {
    type: String,
    required: "User must have a role!",
    enum: ["Operator", "Admin"],
  }
});

In Node:

router.post("/create", async (req, res) => {
  try {
    const user = new User({
      Name: req.body.Name,
      Password: req.body.Password,
      Robots: req.body.Robots,
      Role: req.body.Role,
    });

    await user.save();
    res.send("success");
  } catch (e) {
    console.log(e);
    res.status(400).json("Error" + e);
  }
});

And in React:

try {  
  const userCreated = await axios.post(`${ENDPOINT}/users/create`, user);
  console.log(userCreated);
} catch (e) {
  console.log(e);
}

If it is successful I get back the "success" message, but otherwise I keep getting the POST 400 bad request message.

If I console.log it within node it does throw validation failed errors, but I can't get the error back on the front end.

1 Answers

I tried almost the same example with one of my express boilerplate repo here and I was able to return Mongo validation error like this.

part of an User model

first_name: {
      type: String,
      trim: true,
      minlength: 4,
}

controller

try {
   const user = await new User(req.body);
   const newUser = await user.save();
   res.status(201).json({ status: true, newUser });

} catch (error) {
   console.log(error);
   res.status(400).json(error);
}

Error response I got with 400 Bad Request, so you can check if name == 'ValidationError' in catch of your react app and can also use errors to display with the field.

{
    "errors": {
        "first_name": {
            "message": "Path `first_name` (`a`) is shorter than the minimum allowed length (4).",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `first_name` (`a`) is shorter than the minimum allowed length (4).",
                "type": "minlength",
                "minlength": 4,
                "path": "first_name",
                "value": "a"
            },
            "kind": "minlength",
            "path": "first_name",
            "value": "a"
        }
    },
    "_message": "User validation failed",
    "message": "User validation failed: first_name: Path `first_name` (`a`) is shorter than the minimum allowed length (4).",
    "name": "ValidationError"
}
Related