Node Auth Tutorial (JWT) #5 - Mongoose Validation

Net Ninja
14 Aug 202023:15

Summary

TLDRThis video script discusses enhancing user experience by creating custom error messages for a web application. It covers using Mongoose validation errors and custom error handling to provide users with specific feedback on form submission errors, such as invalid emails or passwords that don't meet criteria. The tutorial also introduces the use of a third-party package 'validator' for email validation and demonstrates how to handle errors in a centralized manner to return a JSON object containing relevant error messages. Additionally, it touches on the importance of hashing passwords using Mongoose hooks to ensure security.

Takeaways

  • 🔒 The script discusses the importance of handling errors in web development to provide clear feedback to users when they submit incorrect data through a form.
  • 📝 Custom error messages are created for different types of validation errors to improve user experience by informing them what needs to be corrected.
  • 👤 Mongoose, a MongoDB object modeling tool, is used to define validation rules and custom error messages for user input fields such as email and password.
  • 📭 A 'validate' property is added to the email field to ensure that the input is a valid email address using a third-party validation package called 'validator'.
  • 🔍 The 'isEmail' function from the 'validator' package is used to validate the email address within the custom validation function in the Mongoose schema.
  • 🔑 The script mentions the use of Mongoose hooks to hash passwords before storing them in the database, emphasizing the security best practice of not storing plain text passwords.
  • 🔄 The process involves creating a function to handle and evaluate errors, which checks the error object to determine the type of validation error and constructs a useful response for the user.
  • 📝 The 'handleErrors' function logs the error message and error code, which helps in identifying the type of validation error encountered during user input submission.
  • 🔑 The script covers how to access and utilize the 'errors' object within the error message to extract specific validation error messages and paths for further processing.
  • 🔄 The 'object.values' method is used to iterate over the errors and extract the necessary information to update an 'errors' object that will be sent back to the user.
  • 📝 Lastly, the script discusses handling the 'duplicate key error', which occurs when a user tries to register with an email that already exists in the database, by providing a custom error message.

Q & A

  • What is the main issue with the current post request error handling in the script?

    -The main issue is that the error handling provides a generic error message regardless of the specific error, which doesn't offer additional information to the user on what needs to be corrected.

  • Why is it important to create custom error messages for different types of errors in a web application?

    -Custom error messages are important because they inform the user specifically what went wrong, allowing them to correct the issue more efficiently rather than guessing what the problem might be.

  • What is the purpose of using Mongoose validation in the script?

    -Mongoose validation is used to enforce data integrity and to provide specific error messages when the data does not meet the defined conditions, such as required fields or minimum password length.

  • How does the script customize error messages for the 'required' field in Mongoose schema?

    -The script customizes error messages by using an array where the first element is the validation condition (e.g., true for required) and the second element is the custom error message to be displayed if the condition fails.

  • What additional property is added to the email field in the Mongoose schema to ensure it contains a valid email address?

    -The 'validate' property is added to the email field with a function that uses a third-party validation package to check if the input is a valid email address.

  • What package does the script use for validating email addresses, and how is it installed?

    -The script uses the 'validator' package for email validation, which is installed using the command 'npm install validator'.

  • How does the script handle the error object caught during user creation in order to provide more useful feedback to the user?

    -The script evaluates the error object to determine the type of error and then creates a JSON object with specific error messages for the email and password fields, which is then sent back to the user.

  • What is the significance of the 'handleErrors' function in the script?

    -The 'handleErrors' function is significant as it processes the error object, extracts the relevant error messages, and returns a structured JSON object containing those messages, which can be used to inform the user of specific validation errors.

  • How does the script differentiate between different types of validation errors in the 'handleErrors' function?

    -The script checks for the presence of 'user validation failed' in the error message and then iterates over the values of the 'errors' object within the error to extract and assign the appropriate error messages to the email and password properties.

  • What is the final step in the 'handleErrors' function after processing the errors?

    -The final step is to return the 'errors' object containing the specific error messages for the email and password, which can then be sent back to the user as a JSON response.

  • How does the script handle the scenario where an email is not unique during user registration?

    -The script checks for a specific error code ('11000') which indicates a duplicate key error. If this error code is present, it sets a custom error message indicating that the email is already registered.

Outlines

00:00

🛠️ Custom Error Handling in Web Forms

The script discusses the need for custom error messages in web forms when incorrect data is submitted via post requests. The current system provides a generic error message, which is not helpful for users. To address this, the video introduces the use of custom error handling combined with Mongoose validation errors. It guides through modifying the Mongoose user schema to include custom error messages for conditions such as required fields and minimum password length. Additionally, it explains the implementation of a 'validate' property for the email field to ensure a valid email address is entered, using a third-party validation package called 'validator'.

05:03

🔍 Evaluating and Handling Mongoose Errors

This paragraph delves into the process of evaluating Mongoose error objects to provide more useful feedback to the user. It points out that the current setup sends a generic error message regardless of the validation error encountered. The script suggests creating a separate function to handle these errors, 'handleErrors', which takes the caught error object and evaluates it to return a JSON object with specific error messages for the email and password fields. The function logs error messages and error codes to the console for debugging purposes and demonstrates how to send back a JSON response with error details to the user.

10:04

📝 Extracting and Utilizing Error Details

The script continues by explaining how to extract detailed error information from the Mongoose error object. It describes looking for the phrase 'user validation failed' within the error message to identify validation errors. The video shows how to create an 'errors' object to store and eventually send back specific error messages to the user. It details the process of using 'object.values' to retrieve the values of the errors and how to iterate over these values to update the 'errors' object with the appropriate messages based on the validation paths ('email' or 'password').

15:06

🔄 Cycle Through Errors for Custom Messages

This section demonstrates how to cycle through the array of error values and extract the necessary information to update the 'errors' object with the correct error messages. It explains destructuring the 'properties' from the error to access the message and path easily. The script then shows how to use the path to determine which property of the 'errors' object to update with the corresponding error message. The goal is to return the 'errors' object from the 'handleErrors' function to be sent back as a JSON response, providing clear and actionable feedback to the user.

20:08

🔒 Handling Unique Email Errors and Future Steps

The final paragraph addresses the specific error handling for non-unique email addresses, which is identified by a 'duplicate key error' code. The script explains that while custom messages can be set for other validation errors, the unique error requires checking the error code and manually setting the email error message to inform the user that the email is already registered. The video concludes by summarizing the error handling process and hints at the next steps, which involve hashing passwords using Mongoose hooks to ensure security by not storing plain text passwords in the database.

Mindmap

Keywords

💡Post Request

A post request is a method to submit an entity to the specified resource, often causing a change in the server state or side effects such as a database update. In the video's context, it is used to send data like user credentials to a server. The script discusses handling errors that occur when incorrect data is sent via post requests.

💡Custom Error Messages

Custom error messages are user-friendly notifications that provide specific information about what went wrong during an operation, such as form submission. The video emphasizes the importance of creating custom error messages to improve user experience by informing them about what needs to be corrected, instead of displaying generic error messages.

💡Mongoose Validation Errors

Mongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It supports validation to ensure that the data being saved to the database meets certain criteria. The script discusses using Mongoose's validation feature to create custom error messages for different types of data validation errors.

💡Error Handling

Error handling is the process of responding to the occurrence of an error in a computer program. The video script describes implementing custom error handling to manage and provide feedback on errors that occur during user data submission, enhancing the clarity and usefulness of the feedback for the end-user.

💡Required Field

A required field is a piece of information that must be provided by the user for a form to be successfully submitted. The script mentions setting 'required' conditions in Mongoose schema to ensure that fields like email and password are not left empty by the user.

💡Minimum Length

Minimum length is a constraint that specifies the shortest acceptable length for a given input, such as a password. The video explains setting a minimum length of six characters for passwords to ensure they are sufficiently complex, and how to provide an error message if this condition is not met.

💡Validator Package

The validator package is a third-party library that provides various string validation functions, including email validation. In the script, the validator package is used to check if the user's input is a valid email address, demonstrating the integration of external libraries for custom validation needs.

💡Unique Constraint

A unique constraint in a database ensures that two entities cannot have the same value for a specified field, such as an email address in a user registry. The script discusses handling errors that occur when a user tries to register with an email that already exists in the database.

💡JSON Object

A JSON (JavaScript Object Notation) object is a structured data format that is commonly used for data interchange on the web. The video script describes sending back a JSON object containing error messages for different fields, which allows for structured and clear communication of multiple errors to the user.

💡Hashing Passwords

Hashing passwords is a security measure that involves converting the original password into a fixed-size string of characters, which is virtually irreversible. The script mentions the importance of hashing passwords before storing them in the database to protect user data in case of a security breach.

💡Mongoose Hooks

Mongoose hooks are functions that can be tied to various lifecycle events of a Mongoose model. They are used for actions like validation, saving, and document modification. The script hints at using Mongoose hooks to hash passwords before they are saved to the database, indicating a proactive approach to security.

Highlights

The video discusses improving user experience by creating custom error messages for different types of validation errors in a web application.

Custom error handling is combined with Mongoose validation errors to provide specific feedback to users.

Mongoose schema is enhanced with custom error messages for required fields and minimum length conditions.

A 'validate' property is introduced to ensure the email field contains a valid email address.

The 'validator' npm package is used for third-party email validation.

A function 'handleErrors' is created to process and return useful error messages to the user.

Errors are evaluated to determine the type of validation failure and corresponding user feedback.

The process of extracting and utilizing error messages from Mongoose's error object is demonstrated.

A JSON object is constructed to send back custom error messages for email and password fields.

The importance of not using camelCase for the 'minLength' property in Mongoose validation is highlighted.

The video shows how to handle unique field errors by checking the error code for duplicate key errors.

A custom message is provided for the case when a user tries to register with an already existing email.

The video concludes with a preview of hashing passwords using Mongoose hooks in the next tutorial.

Storing plain text passwords is discouraged for security reasons, emphasizing the need for hashing.

The tutorial provides a comprehensive approach to improving form validation and user feedback in web development.

Custom error messages are shown to enhance user interaction by providing clear guidance on input corrections.

The use of Mongoose's built-in validation alongside custom error handling is demonstrated for robust form validation.

Transcripts

play00:02

all right then gang so

play00:03

we saw in the last video that currently

play00:05

when we send incorrect data

play00:08

with our post request we get back a

play00:10

blanket error that looks something

play00:12

like this no matter what the error is

play00:14

whether that's an empty email property

play00:16

or the password is too short etc

play00:18

now that wouldn't be great to show a

play00:20

user on a web page because it doesn't

play00:21

offer

play00:22

any additional info so they won't know

play00:24

what to correct instead it would be good

play00:26

to create custom error messages for

play00:29

different types of errors

play00:30

and we'll be using a combination of

play00:33

custom error handling

play00:34

and mongoose validation errors to do

play00:36

this

play00:37

so back in the code we can first come to

play00:40

our mongoose user

play00:41

over here and we can add some custom

play00:44

error messages for the different

play00:45

conditions that we specified like this

play00:47

required so the way we do that

play00:50

is by surrounding this inside an array

play00:53

now the first

play00:54

value of the array is the actual value

play00:56

of this is it required well yes so this

play00:58

is true

play00:59

now we can pass in a second value into

play01:02

the array

play01:02

and that is a custom error message for

play01:05

if this

play01:06

fails so if they don't supply an email

play01:09

then we can trigger an error message

play01:11

which says

play01:12

this thing right here so all i'm going

play01:14

to say right here

play01:15

is please enter an email

play01:19

now i'm going to do the same thing for

play01:22

requires down

play01:23

on the password over here but this time

play01:25

i'm going to change this to

play01:26

password right now i also want to do the

play01:30

same thing for min

play01:31

length so let me surround this in square

play01:34

brackets and again

play01:35

the first position is going to be the

play01:37

value of the min length and then the

play01:39

second

play01:39

position is going to be the error

play01:41

message so i'm going to say minimum

play01:44

password length is

play01:47

six characters right so these are the

play01:50

error messages

play01:51

that we're going to basically throw if

play01:53

these conditions

play01:55

aren't matched when a user tries to

play01:56

submit the form and we try to create the

play01:59

user

play01:59

right now we also need for the email

play02:03

an extra property right here called

play02:06

validate

play02:07

now the reason i'm doing this is because

play02:09

we want our email to be a valid email

play02:11

address at the minute they could just

play02:12

type in

play02:13

any string like a name and there's

play02:15

nothing here that says

play02:16

otherwise so i could just type in mario

play02:19

and

play02:19

well it's a string it's there we've

play02:21

typed something in

play02:22

it's unique it's not in the database and

play02:24

we've turned it to lowercase but there's

play02:26

nothing saying

play02:26

it has to be an email so we can add this

play02:30

validate property to any different field

play02:33

inside our schema

play02:34

and this is going to be an array again

play02:37

the first position in this

play02:38

is going to be a function so i could

play02:41

create a function

play02:42

right here which does something in here

play02:44

some custom validation

play02:46

now inside this function we

play02:47

automatically take in a value and that

play02:50

value is the value of the user email

play02:52

that is submitted to whatever the user

play02:54

types

play02:54

when we click submit so we take that

play02:56

value and we can

play02:58

validate it inside this function now

play03:00

we'd return true

play03:01

if we think it's valid and it passes we

play03:03

return false if we think it's not valid

play03:06

and in that case we would throw an error

play03:08

with this error message the second

play03:10

position

play03:10

in the array so i could say please

play03:14

enter a valid email so

play03:17

inside this function you would want to

play03:19

do something to validate that email

play03:20

so to do this we could use a regular

play03:22

expression for email and match it

play03:24

against what a user submits

play03:26

but also we could just use a third-party

play03:29

validation package

play03:30

which is what i'll do so this package is

play03:33

called

play03:33

validator and i'm going to install it

play03:35

first of all so

play03:36

we need to create a new console and i'm

play03:39

going to say npm

play03:40

install validator now

play03:43

if you've got an old version of node and

play03:46

npm then you need to pass in the save

play03:48

flag

play03:48

like so to save it to your dependencies

play03:50

i've got a newer version so i don't need

play03:52

to do that

play03:52

and it's automatically going to register

play03:54

it inside my dependencies

play03:56

right here okay so now we have that

play03:59

installed

play04:00

the next thing to do is import something

play04:02

from that package at the top over here

play04:05

so this package has different functions

play04:07

inside it that we can use to validate

play04:09

different things

play04:09

and one of those things is to validate

play04:12

an email

play04:12

so i want to import that function to

play04:15

validate an email

play04:16

from the validator package so i'm going

play04:19

to say const

play04:20

and d structure to get the is email

play04:23

function so this is coming from the

play04:26

validator package

play04:28

we just installed so all we need to do

play04:31

down here now

play04:32

is instead of creating our own function

play04:35

just passing

play04:36

is email like so now this triggers a

play04:39

function and it automatically passes

play04:41

that value into it

play04:43

that a user submits for the email and

play04:45

then this

play04:46

looks at that value and it returns true

play04:48

if it is a valid email

play04:49

false if it's not a valid email okay

play04:52

so that's pretty much it for our custom

play04:55

errors

play04:56

right here we will come back to this one

play04:57

later on because we're going to handle

play04:58

that

play04:59

slightly differently but for now this

play05:02

will do

play05:03

now before we go any further i have just

play05:05

noticed an

play05:06

error right here this min length

play05:08

property should not be camelcase and

play05:10

this l should not be a capital letter

play05:12

make sure that is a lowercase otherwise

play05:14

this won't work okay so now we have all

play05:16

of these different validation messages

play05:18

but at the moment

play05:19

they are not really doing anything if we

play05:22

were to send

play05:22

a request with invalid data we would

play05:25

still get back this blanket error

play05:26

message

play05:27

as we can see right here and that's

play05:29

because in the auth controller we're

play05:31

sending that right here so we're kind of

play05:33

ignoring this error object that we catch

play05:35

and that error object contains this kind

play05:38

of

play05:38

information on it so what we really want

play05:41

to do

play05:41

is evaluate this error object to see

play05:43

what kind of error

play05:44

is and then send back to the user

play05:46

something more useful

play05:48

like one of these messages or if there's

play05:51

several errors

play05:52

for example an error for the email and

play05:53

an error for the password

play05:55

send back both of those messages so

play05:58

ultimately i'd like to send back an

play06:00

object right here a json object instead

play06:02

of just a string

play06:03

and that json object will contain a

play06:05

password property

play06:06

and an email property now the password

play06:09

property will hold the password error if

play06:11

there is one

play06:12

or a blank string or an empty string if

play06:14

there's not an error

play06:15

and the email property will contain the

play06:17

email error if there is one

play06:19

so all of this evaluating of this error

play06:22

object right here

play06:23

should probably be done in a separate

play06:25

function so we're not bloating our code

play06:26

right here

play06:27

and duplicating code later on when we do

play06:29

a similar thing down here

play06:30

so let us now create a function at the

play06:33

top of this file

play06:34

to handle these errors so handle errors

play06:37

and we'll create a const called handle

play06:41

errors and that is going to take in the

play06:43

error object that we catch

play06:45

down in the try catch block right here

play06:48

so what we can do now is just call that

play06:49

function handle errors

play06:51

and pass in the error object so up here

play06:55

this is where we're going to evaluate

play06:56

the error object and return

play06:58

a more useful object which we can then

play07:01

send back as json to the user

play07:03

now to begin with all i'm going to do is

play07:05

log to the console

play07:07

the error message now the message

play07:10

property comes on all of the errors that

play07:12

we get

play07:13

and it contains information about what

play07:15

type of error this is

play07:17

now i'm also going to log out something

play07:18

else and that is the error code

play07:20

now this code property doesn't exist on

play07:22

most of the areas that we're going to

play07:23

get

play07:24

but it does exist on one specific error

play07:26

that we're going to handle in the future

play07:28

in particular that is the unique error

play07:31

but we'll come to that later on

play07:33

most of the time this will be undefined

play07:35

but later we will

play07:36

need it okay so let's just take a look

play07:39

at this error message

play07:40

when we send some invalid data so

play07:44

let me first of all go over here and

play07:45

press send and then

play07:47

if we go back to the code we should see

play07:50

down in the console if we open up the

play07:52

other terminal

play07:53

this thing right here so this is the

play07:55

error message

play07:57

and it contains user validation failed

play08:00

and then it says please enter an email

play08:01

and also please enter a password

play08:03

this right here this is the error code

play08:06

like i said undefined

play08:07

for the most part okay so this

play08:10

is if we don't enter an email and if we

play08:12

don't enter a password but what if we

play08:14

enter in something like mario which is

play08:16

not a valid email

play08:17

and also just one two three which isn't

play08:20

at least six characters long

play08:21

so this should still fail on two

play08:23

accounts right because

play08:25

inside the model it must be a valid

play08:27

email and it must be at least

play08:29

six characters long so let me send

play08:32

this request and over here we can see

play08:35

again

play08:36

user validation failed so this is the

play08:38

same in both

play08:39

instances and this time it says please

play08:42

enter a valid email

play08:43

not please enter an email and it says

play08:45

the minimum password length is six

play08:47

characters

play08:48

again the code is undefined so the

play08:50

common thing here is

play08:51

this string right here user validation

play08:54

failed

play08:55

so anytime there's any kind of error

play08:57

which is dictated by

play08:58

any one of these fields right here

play09:00

required validate

play09:02

required and min length then the error

play09:04

message that we get is going to contain

play09:07

this thing right here so we can look

play09:10

for the presence of this in the error

play09:12

message in order to handle these kind of

play09:14

errors

play09:15

in a particular way so let's do that

play09:18

down here the first thing i'm actually

play09:21

going to do is

play09:22

create an errors object so errors is

play09:24

equal to an object and inside here we'll

play09:27

have an email property

play09:28

which will be an empty string to begin

play09:30

with and a password property which will

play09:32

be an

play09:32

empty string to begin with as well now

play09:35

eventually

play09:35

this is the thing that will be sent as

play09:37

json back to the user

play09:39

so if there's an email error we'll

play09:41

update this property

play09:42

if there's a password error we'll update

play09:44

this property we're going to return that

play09:46

at the end of this function so that down

play09:49

here

play09:50

we can store it in a constant by saying

play09:52

const errors is equal

play09:54

to whatever this function returns and

play09:57

then we can

play09:57

send that as a response right here as

play10:00

json right

play10:01

so this is what we need to populate now

play10:04

dependent on the errors

play10:06

so let's look for the presence of this

play10:08

user validation failed

play10:09

inside this error message first of all

play10:12

so

play10:12

first of all i'll do a little comment to

play10:15

say validation errors

play10:18

i like that and then i'm going to say if

play10:21

and we're going to take a look at the

play10:22

error

play10:23

message and we're going to see if that

play10:25

includes

play10:26

a certain phrase and that phrase is

play10:28

going to be this

play10:29

thing right here so let me grab that

play10:32

copy it and paste it in here

play10:34

and now if this is the case then we can

play10:37

do something

play10:38

with that error now all i'm going to do

play10:41

for now is

play10:41

log that to the console console.log the

play10:44

error just so that we can see it

play10:46

so if i save this now and try to send

play10:50

a request like this with invalid data so

play10:52

send that

play10:53

and both fields are invalid right let's

play10:56

take a look at this object

play10:58

now it is quite messy to see right here

play11:00

in the console it's not

play11:02

a great way of looking at them but

play11:04

hopefully we will see this in a second

play11:06

so this is the error object right here

play11:09

so first of all we get the error message

play11:11

at the top right this is the thing where

play11:13

it says user validation failed

play11:15

please enter an email please make sure

play11:17

the minimum password length is six

play11:19

characters etc

play11:20

now down here we can actually see inside

play11:23

the error object we have another

play11:26

property called

play11:27

errors so inside this object we have

play11:30

the different errors that is created

play11:34

by this request now there should be two

play11:36

of them because this validation will

play11:37

fail

play11:38

and this will fail as well so inside

play11:39

this error object or errors object

play11:41

rather

play11:42

there should be two properties one for

play11:44

email and one for password

play11:46

so if we scroll down a little bit we can

play11:48

see right here the first one

play11:50

email right so we can see there's a

play11:52

validator error

play11:53

please enter a valid email and down here

play11:56

on this email object as well we see

play11:58

other things we have a properties

play12:00

property and we'll need that in a second

play12:02

we also have

play12:03

the path and the path basically says

play12:06

what property

play12:07

that we're failing on so the email in

play12:09

this case uh the value which is what i

play12:11

use entered etc

play12:13

so that's the first object inside the

play12:16

errors

play12:16

object okay so the second one

play12:19

is the password because we had an error

play12:21

for the password as well and that's a

play12:23

minimum length

play12:24

error so again down here we have the

play12:26

properties which we'll need in a second

play12:28

we'll take a look at that in a minute

play12:30

and we also have the kind of error well

play12:32

it's a min length error

play12:33

the path so what field failed and that

play12:36

was the password one

play12:37

and the value that a user tried to

play12:39

create and that was one

play12:40

two three right so ultimately remember

play12:44

the end game here

play12:45

is to populate this with an email error

play12:48

and a password error if there are them

play12:50

okay so

play12:52

really what we want to do is access

play12:54

inside

play12:55

this error object right here the errors

play12:59

property this thing right here this

play13:01

errors property contains the errors it's

play13:03

got two keys in it email

play13:04

and password and both of those then

play13:07

contain information about

play13:08

those individual errors so

play13:11

we need to take this errors property

play13:14

right here

play13:15

and we want to get the values of each

play13:18

one of these things inside it we don't

play13:20

necessarily need the key

play13:21

we want the values of each key inside it

play13:24

so how can we get those

play13:26

well what we can do is we can use

play13:28

object.values and then pass in this

play13:30

errors object and that gets us the

play13:32

values

play13:33

of both of the different fields inside

play13:36

it so this

play13:37

value with the properties the kind the

play13:39

path and also

play13:40

this value from the password

play13:43

so let me just do that first of all let

play13:45

me log those to the console console.log

play13:48

and we want the error overall object

play13:51

then we want the errors

play13:52

object inside that which is this thing

play13:55

right here

play13:56

and then we want the values of those

play13:58

properties

play13:59

so the way we do that is by saying

play14:00

object dot values and then surrounding

play14:03

this

play14:03

okay so it takes this object right here

play14:07

this errors object and it gets us the

play14:09

values

play14:10

of the different things inside that

play14:12

object so not

play14:14

the keys but the values so if i log that

play14:17

to the console now if i save it

play14:19

and just quickly this must be a capital

play14:22

o otherwise this won't work so save that

play14:24

again

play14:24

and now let's try sending a request

play14:27

and if we go back we should be able to

play14:30

see

play14:30

these different values so we can see we

play14:33

have

play14:34

these different objects right here so

play14:35

let me just show you we have this

play14:38

array and the first one the first object

play14:41

is right here with the different

play14:42

properties and other information

play14:44

and remember these properties are

play14:45

ultimately what we want to get because

play14:47

they contain the message that we write

play14:49

and also the path to say what property

play14:52

we need to update

play14:54

and the second one down here is for the

play14:56

password

play14:57

so we have again the properties with the

play14:59

message inside it

play15:00

and the path etc okay so we want those

play15:04

ultimately but now we have an array

play15:06

of the values so what we could do is we

play15:08

could actually

play15:09

cycle through that array of values

play15:12

right here and then for each one of them

play15:15

extract the information that we need

play15:17

and update these different properties so

play15:20

let me now say

play15:21

for each on these so we can do that

play15:23

remember because this is an array

play15:25

and for each one we'll take in the

play15:27

individual

play15:28

error and inside here i'm going to just

play15:33

console.log

play15:34

the error and i'm going to log the

play15:36

properties property

play15:38

on each one of them all right so error

play15:40

dot properties

play15:42

like so so let me save that again and

play15:45

come and try to send a request

play15:47

that's not valid again and if we come

play15:50

back over here

play15:51

now if we scroll down we should have two

play15:54

objects right here

play15:55

we have this one and we have this one so

play15:58

this is ultimately

play15:59

what we need so for each one of these

play16:01

now we can say okay well the path is

play16:03

email so this is

play16:04

an email error so i'll take this

play16:06

property right here

play16:07

and we're going to update that and i'll

play16:09

set the message or the value of that

play16:11

property

play16:12

to be this thing right here and i can do

play16:14

the same

play16:15

for this one as well i'll say well okay

play16:17

this time the path is password so i'll

play16:19

update the password property

play16:20

and i'm going to set the value of that

play16:22

equal to this thing okay

play16:24

so what i could do is instead of

play16:28

passing in the error right here i could

play16:30

destructure

play16:31

and get the properties

play16:35

from the error like that and to do that

play16:37

i need to place this in parentheses

play16:40

so now all we're doing is destructuring

play16:41

the properties property

play16:43

from the error and now we have access to

play16:45

that without saying error.properties

play16:47

this does exactly the same thing and i

play16:49

can demo that

play16:51

by sending a request again

play16:54

and over here we get the two same values

play16:57

so these are the properties objects

play16:58

right

play16:59

okay so we have those now what is the

play17:02

next step

play17:03

well all i want to do now is access the

play17:05

errors that i have

play17:07

right here or the error object rather

play17:09

and

play17:10

then i need to decide which property i

play17:13

want to update

play17:14

well to do that i can pass in a string

play17:17

inside

play17:17

square brackets so for example i could

play17:19

say email right here

play17:20

and set that equal to some value and

play17:23

that would

play17:24

take this property right here the email

play17:26

based on this

play17:27

and it would update it with this value

play17:29

now instead of passing through email i

play17:31

can get

play17:32

that from the properties path property

play17:34

right here

play17:35

so i'm going to say properties

play17:39

dot path so that's either going to be

play17:41

email or

play17:42

password right so it's going to take

play17:44

whatever property that is and

play17:46

update it with something now i want to

play17:48

update it with

play17:49

the message so i can say properties

play17:53

dot message like so and that's all there

play17:56

is to it

play17:57

now we're updating this error object

play18:00

right here and in fact

play18:01

i'm going to call this errors instead of

play18:03

error makes more sense because there

play18:04

could be more than one

play18:06

so update it here and here so we're

play18:08

updating those with

play18:09

the different messages we have and if

play18:11

there's only one of these

play18:13

then we're just going to cycle through

play18:14

the one of them and update that

play18:16

particular property the other one

play18:17

will remain blank meaning there's no

play18:19

error all right

play18:21

now at the end of all of this we want to

play18:23

return the errors

play18:24

object that we have right here so let's

play18:27

do that

play18:28

so i'm going to save this now and if we

play18:30

scroll down

play18:32

then we're getting those errors right

play18:34

here because we're returning them from

play18:35

this function

play18:36

and now we can send back some json

play18:39

instead of just some text so

play18:41

dot json and inside we want to send back

play18:44

some json

play18:45

and that is basically going to be the

play18:48

errors that we have

play18:49

okay so that's all there is to it we're

play18:51

sending now this thing

play18:52

up here back to the user in json format

play18:56

after we've populated the different

play18:58

values so let's try this

play19:00

and come over here so we need to send a

play19:03

new request now and hopefully we should

play19:05

see an error for this and an error for

play19:07

this

play19:07

so send and we see please enter a valid

play19:10

email

play19:10

and minimum password length is six

play19:12

characters so

play19:14

let's do an email so at google.com

play19:17

and press send and that value goes away

play19:21

that error but we still have this one

play19:23

so let's do test123 instead

play19:26

and press send and hopefully

play19:29

yep this works and we get the user back

play19:31

that mongodb creates

play19:33

for us okay so there's one more error

play19:36

that we need to handle

play19:37

and that is to do with whether an email

play19:40

is unique

play19:41

so if i try to do this again and click

play19:43

send

play19:44

then i'm going to get some errors right

play19:46

here but

play19:48

this time we don't have any information

play19:50

here so we don't really know what the

play19:52

error is

play19:53

now the error is that this has to be

play19:55

unique remember we specified that inside

play19:57

the user controller over here where we

play20:00

said unique is true

play20:01

now unfortunately we can't do a custom

play20:04

message over here for an error like the

play20:08

other ones

play20:08

over here we can't do that with unique

play20:11

instead what we have to do

play20:12

is look for information about this error

play20:16

over here and that information is the

play20:18

error code

play20:19

so notice when i sent this request over

play20:21

here we get this error code right here

play20:24

and it says

play20:24

duplicate key error so basically this is

play20:27

saying that

play20:28

this email that you're trying to sign up

play20:30

with should be unique

play20:31

and this email already exists in the

play20:33

database and if we take a look inside

play20:36

the database

play20:37

if i scoot this down and go to mongodb

play20:40

i'm going to refresh over here

play20:42

we should now see mario at google.com

play20:45

as a user so it won't create that again

play20:49

and that's a good thing but we do need

play20:50

to update the error

play20:52

for this so we can look for this code

play20:54

and we can

play20:55

react to that and send back a custom

play20:57

error based on that

play20:59

so let's do that now i'm going to say

play21:00

duplicate

play21:02

error code and underneath this i'm going

play21:05

to say if

play21:07

error.code is triple equal to 1 1

play21:10

0 0 0 so that's this thing over here

play21:14

then we're going to do something so the

play21:17

thing we want to do

play21:18

is update this property so i'll say

play21:20

errors

play21:22

dot email is equal to some kind of

play21:25

string and i'll say that

play21:26

email is already registered all right

play21:30

so at this point we can just return

play21:33

the errors like so there's no need to go

play21:35

any further and check these errors as

play21:37

well because we already have this

play21:38

whopping error

play21:39

and we can tell that to the user so

play21:41

we're returning errors here

play21:43

if this is the case otherwise we return

play21:45

them at the bottom after we've done all

play21:46

of this jazz

play21:47

are right here so let's save this and

play21:50

see if this works

play21:51

so if i go back over to oops i need

play21:54

postman

play21:55

so if i try to request this again send

play21:59

it should say that email is already

play22:01

registered

play22:02

all right then cool so now we've sorted

play22:04

all of our errors out by using this

play22:06

error handler function

play22:07

at the top right here now this bit right

play22:10

here i know

play22:11

was a little kind of long-winded and a

play22:13

little bit complex but it's just a way

play22:16

to create custom messages there are

play22:18

other ways to handle errors as well

play22:20

and you might have your own preferred

play22:22

way this is just one way by cycling

play22:24

through the values of the errors

play22:26

finding the message for each one and

play22:28

updating an errors object

play22:30

with that message right here so we have

play22:33

all of these errors

play22:34

sorted out now eventually we will show

play22:37

all of the errors on the web form

play22:39

after a user submits it whether that be

play22:40

the login form or the signup form

play22:42

and we will create those forms

play22:44

eventually but next up before we create

play22:46

the forms

play22:46

i want to show you first of all how to

play22:48

hash passwords

play22:50

and for that we're going to be using

play22:51

mongoose hooks because

play22:53

we never really want to store

play22:56

plain text passwords over here in the

play22:59

database that is a

play23:00

bad bad idea in case your database is

play23:03

compromised

play23:04

and all of your passwords are then on

play23:05

show so we'll be hashing those passwords

play23:07

first of all

play23:08

and we'll see how to do that or how to

play23:10

start that process at least

play23:12

in the next video using mongoose hooks

Rate This

5.0 / 5 (0 votes)

Related Tags
Web DevelopmentForm ValidationCustom ErrorsMongoose SchemaUser ExperienceError HandlingData ValidationWeb FormsFrontend DesignBackend Logic