Sarthak Virmani
Sarthak Virmani

Reputation: 103

How to fix ' ValidationError: users validation failed: name: Path `name` is required.' error in Mongo?

I'm creating a new user and checking whether the user email previously exists or not. If not then it is creating a new user and saving it. What do I need to correct this validation error I am getting?

I have already tried by setting name as not required. But it still does not work.

This is my User model.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

//Declaring User Model
const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  avatar: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = User = mongoose.model("users", UserSchema);

This is the user route.

router.post("/register", (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json({ email: "email already exists" });
    } else {
      const avatar = gravatar.url(req.body.email, {
        s: "200", //size
        r: "pg", //rating
        d: "mm" //default
      });
      const newUser = new User();
      const newUser = {
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      };
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});

I am expecting it to get stored. This is the error I am getting.

{ ValidationError: users validation failed: name: Path `name` is required.
    at ValidationError.inspect (G:\devconnector\node_modules\mongoose\lib\error\validation.js:59:24)
    at formatValue (internal/util/inspect.js:493:31)
    at inspect (internal/util/inspect.js:191:10)
    at Object.formatWithOptions (util.js:84:12)
    at Console.(anonymous function) (console.js:191:15)
    at Console.log (console.js:202:31)
    at newUser.save.then.catch.err (G:\devconnector\routes\api\users.js:39:35)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  errors:
   { name:
      { ValidatorError: Path `name` is required.
          at new ValidatorError (G:\devconnector\node_modules\mongoose\lib\error\validator.js:29:11)
          at validate (G:\devconnector\node_modules\mongoose\lib\schematype.js:1034:13)
          at G:\devconnector\node_modules\mongoose\lib\schematype.js:1088:11
          at Array.forEach (<anonymous>)
          at SchemaString.SchemaType.doValidate (G:\devconnector\node_modules\mongoose\lib\schematype.js:1043:14)
          at G:\devconnector\node_modules\mongoose\lib\document.js:2133:9
          at process._tickCallback (internal/process/next_tick.js:61:11)
          message: 'Path `name` is required.',
          name: 'ValidatorError',
          properties: [Object],
          kind: 'required',
          path: 'name',
          value: undefined,
          reason: undefined,
          [Symbol(mongoose:validatorError)]: true } },
          _message: 'users validation failed',
          name: 'ValidationError' }

Upvotes: 7

Views: 51116

Answers (8)

Gabriel Arghire
Gabriel Arghire

Reputation: 2360

In my case, I was using the create method together with

{ upsert: true, new: true }

I deleted this line and the error was gone.

Upvotes: 0

Neeraj chaudhary
Neeraj chaudhary

Reputation: 1

  axios.post(`${API}/create-user`,data,{
        headers: {
            'Content-Type': 'application/json',
            'token': localStorage.getItem('token')
          }
    })
    .then((res)=>{
        console.log(res)
        alert("User created successfully")
    }).catch((err)=>{
        console.log(err)
    })

changed multipart/formdata to application/json

Upvotes: -1

Arjun
Arjun

Reputation: 1

Solution to the above problem is simple, you just need to tweak some options in the postman tool. When you POST the JSON data from postman, make sure you select JSON from the dropdown as shown in the snapshot.

Upvotes: 0

Veerendra
Veerendra

Reputation: 81

The above issue will be cleared when you set the content-type to application or json in the post man then you can check it, will work normally with out producing error, I have faced the above error, I do the same it fixed my issue.

Upvotes: 0

MUHAMMAD SHAHID RAFI C P
MUHAMMAD SHAHID RAFI C P

Reputation: 1229

Ensure your api post body contain the proper json keys and value pair for creating a new documents as per the mongoose model.

Upvotes: 0

jordy bayo
jordy bayo

Reputation: 449

the solution is so simple, now and in thew future avoid using additionnal parameters, you don't need them

const userSchema = mongoose.Schema({
    email: String,
    username: String,
    password: String,
    googleId:   String,
    avatar_url: String,
});

Upvotes: 1

nitin kumar
nitin kumar

Reputation: 11

Faced similar issue, got resolved by adding these lines in app.js:

app.use(
    express.urlencoded({ extended: true })
);
    
app.use(express.json());

Upvotes: 0

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

In your code I can see that you are setting newUser as User() model object, then setting that to a plain javascript object. Which is wrong syntactically as well.

Basically you need make the model object with the values.

const newUser = new User({
   name: req.body.name,
   email: req.body.email,
   avatar,
   password: req.body.password
});

Upvotes: 11

Related Questions