Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I print a property value in the error object?

I’m making a simple user register web app. I’m using MongoDB and Express JS to register new users and save them in the database.

I’ve put a few validation properties in the schema, whenever a user fills invalid data that doesn’t follow the schema, a validation error will be displayed in the console.

Now, what I’m trying to do is that the validation error that is written in the console has two properties that I want, which are "path" and "kind", so I can display these two in the browser for the user to see.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I get just the "path" and the "kind" properties out of the error object? I don’t want the whole error message printed, I just want these two properties.

I tried using console.log(err.path) and console.log(err.kind), but they both return undefined.

I couldn’t figure out how to access those two properties.

// Post new user (REGISTER):
router.post('/signup', async (req, res) => {

    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;

    try {
        await User.create({username, email, password})
    } 

    catch(err) {

// I don't want the whole err, I just want err.path and err.kind if possible!
        console.log(err);
    }

});

enter image description here

>Solution :

The following should work. These properties are within a nested object, held by keyword errors

console.log(err.errors.username.kind, err.errors.username.path)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading