'How can i get specific error messages from a Mongoose Schema?

I am trying to set up user validation in Mongoose and struggling to get the specific messages to appear. Here is my model

const userSchema = new Schema({
    name: { 
        type: String, 
        required: [true, "Name required"]
    },
    email: { 
        type: String, 
        required: [true, "Email required"] 
    },
    password: { 
        type: String, 
        required: [true, "Password required"],
        minlength: [6, "Password must be at least six characters"]
     },
    date: { type: Date, default: Date.now },
    albums: [{ type: Schema.Types.ObjectId, ref: "Album"}]
})

I currently have this method to create a new user. I believe I will need to find a better way of seeing if the email exists, probably in the model, but for now this is what I have.

registerUser(req, res) {
    const { name, email, password } = req.body
    db.User.findOne({ email: email })
        .then(exists => {
            if (exists) res.redirect("/register")
            else {
                db.User.create({ name, email, password })
                    .then((err, res) => {
                        if (err) console.log(err.errors.password.message)
                    })
            }
        })
},

I am entering an invalid password length to try and get the message, but I get a large error:

(node:49238) UnhandledPromiseRejectionWarning: ValidationError: User validation failed: password: Password must be at least six characters
[0]     at model.Document.invalidate (/Users/user/Desktop/untitled folder/portfolio-projects/project/node_modules/mongoose/lib/document.js:2579:32)
[0]     at /Users/user/Desktop/untitled folder/portfolio-projects/project/node_modules/mongoose/lib/document.js:2399:17
[0]     at /Users/user/Desktop/untitled folder/portfolio-projects/project/node_modules/mongoose/lib/schematype.js:1220:9
[0]     at processTicksAndRejections (internal/process/task_queues.js:79:11)
[0] (node:49238) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
[0] (node:49238) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

What do I need to change in order to receive just the error message?



Solution 1:[1]

I had issues in the past regarding this and this helped me solve the issue

if (err) {
    if (err.name === 'ValidationError') {
        console.error(Object.values(err.errors).map(val => val.message))
    }
}

This will return Password must be at least six characters

Update-

First you need to fix your code as you are mixing promises with callbacks as if you are using .then syntax you don't have (err,res) object here

cleaner way to do it is

registerUser(req, res) {
    const {
        name,
        email,
        password
    } = req.body
    db.User.findOne(email)
        .then(exists => {
            if (exists) res.redirect("/register")
            else {
                db.User.create({
                        name,
                        email,
                        password
                    })
                    .then(res => {
                        console.log(res);
                    }).catch(err => {
                        if (err.name === 'ValidationError') {
                            console.error(Object.values(err.errors).map(val => val.message))
                        }
                    })
            }
        }).catch(err => console.error(err))
};

You can further clean it up using Async/Await like this

async registerUser(req, res) {
    const {
        name,
        email,
        password
    } = req.body
    try {
        const userExist = await db.User.findOne(email);
        if (userExist) {
            res.redirect("/register")
        } else {
            const createdUser = await db.User.create({
                name,
                email,
                password
            })
            res.redirect('')
        }
    } catch (err) {
        if (err.name === 'ValidationError') {
            console.error(Object.values(err.errors).map(val => val.message))
        } else {
            console.error(err);
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1