1

I'm trying to register users using node and mongo but I get this ValidationError:

unhandledPromiseRejectionWarning: ValidationError: user validation failed: password: Path password is required., username: Path username is required., email: Path email is required.

this is my signup function.

exports.signup =   async function (request, res, next) {

    try {
        let user =  await db.User.create(request.body);
        console.log(user);
        let { id,email,username } = user;
        let token = jwt.sign({
            id,
            email,
            username
        },
            process.env.SECRET_KEY 
        );
        return res.status(200).json({
            id,
            username,
            token
        })
    } catch (err) {
        if (err.code === 11000) {
            err.message = "sorry, username/email are token";
        }
        return next({  
            status: 400,
            message: err.message
        })
    }

this is my user model

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true,
    },
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
    },
    profileImageUrl: {
        type: String,
    },
    messages:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Message'
    }]
})

userSchema.pre('save', async function (next) {  
    try {
        if (!this.isModified('password')) {
            return next();
        }
        let hashedPassword = await bcrypt.hash(this.password, 10);
        this.password = hashedPassword;
        return next();
    } catch (err) {
        return next(err);
    }
});

const User = mongoose.model("user", userSchema);
module.exports = User;

NOTE: I'm using Postman to test this.

Amine
  • 57
  • 7

2 Answers2

2

So yeah I found the problem. the fields are required so if you try to insert a new user with empty fields you get that error. The fields were empty because The 'body-parser' middleware only handles JSON and urlencoded data, not multipart. So I had to change my index file to

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

I also changed the content type in Postman to "X-www-form-urlencoded". Now the request body is populated and the user is inserted correctly

Amine
  • 57
  • 7
0

I also faced this error. In your user model remove required:true in all fields like this:

email: {
    type: String,
    unique: true
}
Reza Rahemtola
  • 1,182
  • 7
  • 16
  • 30
divya
  • 1