'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.
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);
}
});
Solution 1:[1]
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)
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 |

