Search code examples
node.jsmongodbexpressmongoose

Node JS + Mongo DB: ValidationError: User validation failed: username: Path `username` is required


When I am trying to Save/Create a New Document (User) to Mongo DB using Mongoose, I am getting the following Validation Error in spite of providing all the Values with proper DataType:

ValidationError: User validation failed: username: Path `username` is required.

I have also added the following modules:

  • Express
  • Mongo
  • Mongoose
  • Body Parser

Please see below for more details:

Detailed Error:

{
"errors": {
    "username": {
        "message": "Path `username` is required.",
        "name": "ValidatorError",
        "properties": {
            "type": "required",
            "message": "Path `{PATH}` is required.",
            "path": "username"
        },
        "kind": "required",
        "path": "username",
        "$isValidatorError": true
    }
},
"_message": "User validation failed",
"message": "User validation failed: username: Path `username` is required.",
"name": "ValidationError"
}

User Schema / Model:

var mongoose = require("mongoose");

var userSchema = new mongoose.Schema({
firstName: {
    type: String,
    required: true
},
lastName: {
    type: String,
    required: true
},
username: {
    type: String,
    unique: true,
    required: true
},
password: {
    type: String,
    required: true
}
});

mongoose.model("User", userSchema, "users");

User Controller:

var register = function (req, res) {

console.log("Registering User.");

var firstName = req.body.firstname;
var lastName = req.body.lastname;
var userName = req.body.username;
var password = req.body.password;

User
    .create({
        firstName: firstName,
        lastName: lastName,
        userName: userName,
        password: password
    }, function (err, user) {
        if (err) {
            console.log("Error creating User: ", err);
            res
                .status(400)
                .json(err)
        } else {
            console.log("User Created: ", user);
            res
                .status(201)
                .json(user)
        }
    })
};

Why am I getting this Validation Error and how to resolve it?


Solution

  • You made a typo:

    User
        .create({
            firstName: firstName,
            lastName: lastName,
            username: userName, // the property is "username" in model
            password: password
        }, function (err, user) {
            if (err) {
                console.log("Error creating User: ", err);
                res
                    .status(400)
                    .json(err)
            } else {
                console.log("User Created: ", user);
                res
                .status(201)
                .json(user)
            }
        })
    };