Complete Node.js Express MongoDB CRUD

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
quick demo of this video tutorial in this video we are going to implement correct operations insert update and delete inside a node.js application with the help of Express and dB so here we have the final output from this tutorial in order to insert in your code you can click on this button here then populate the form now let's submit the form so here we have the updated employee list in order to edit this report you can click on this pencil icon here then make the required changes and submit the form so here we have updated the corresponding employee record in order to delete the record you can click on this trash icon here then it will ask for confirmation are you sure to delete this report or not click on OK so here we have deleted the corresponding employee record inside this project we will be using template engine handlebars we will design these views using express handlebars apart from these we will discuss how to implement form validation inside the project so there are a lot of things to learn from this tutorial please watch till the end of this video tutorial before starting this video I would like to ask you a favor if you found this video helpful please thumbs up this video if you are new here please please subscribe to this channel and click on the bell icon to get notification about my new videos most of the video LSN here also has a written blog post you can find the link in video description you can grab code from the as well what's up YouTube welcome to coda friction in this video we will implement crud operations insert update and delete inside a node.js application with the help of Express and MongoDB without further ado let's get started here is my visual studio code editor I will be using this IDE for this project I'm going to create the project inside this project folder here so let me copy this for the path from here then back to the IDE then click on open folder and I will paste the directory here then select the folder in order to create a node.js application we have to run npm init command from the terminal i will be using this terminal from this ide or you can use the command prompt also now let's run the command npm init hit enter then it will ask few configuration details about the project if you don't want to change those options just hit and Oh through them for entry point I will be using a javascript file with the name server dot J's so here we have done with the configuration finally we just need to type yes then hit enter as a result of this NPM minute command execution we have created this packaged or JSON file here now let's install required packages for this project first of all we have the Express train work itself and we have Mongoose which is a no atom or object relational mapping package which helps to work with mongoose DB from node.js applications then we have Express handlebars inside this node.js application we don't have a separate kind side like react or angular so we will be using a template engine for this project it will be handlebars here we have the parent package handlebars since we are working with express it would be better if we use this package express handlebars so we will be using Express handlebars instead of handlebars and finally we have this body posture package which is useful for the conversion of post data into request body now let's install these four packages for that we have to run this command and PM I for installation in order to save these dependencies inside the package tortoise and file we have to use this flag save or in short you can use double - yes first of all we have the Express package now let me include the latest version number which is here I will copy this in order to specify the version number we have to use this at the rate symbol then paste diversion here then we have Mongoose I will copy this version here and then we have Express handlebars finally we have Bodie pasa now hit and OH so here we have successfully installed those four packages here as a result of that you can see this dependencies object inside this package door JSON file here before continuing with this node.js project let's set up a database inside MongoDB so first of all we have to start this server for that we need to execute these commands here first of all we will navigate inside the MongoDB installation file directly with this CV command and we have to start this exe B dot exe with this parameter DB part here we have given the physical directory where we want to save the data in order to start the server we have to execute these commands from the command prompt or you can type these commands inside a notepad then you can save that as a be a T or batch file like this then you just need to double click on this file so it will start the MongoDB server from this default port number two seven zero one seven so this be a T file is a best practice in order to avoid repetition of typing these two commands in your command prompt as a management tool for this MongoDB I will be using this tool MongoDB kompis community here we have the connection with that I will connect the MongoDB with these default configurations here click on connect now let's create a database inside this project we will be dealing with employee duties so I will name this database as employee DB along with database name we have to provide a collection name I will give employees now let's create the database now back to me a score editor now let's look how we can connect this MongoDB from this node.js application you see mongoose package for that first of all i will create this folder models inside that I will create a JavaScript file DB dot J's first of all we have the request statement for Mongoose with this constant Mongoose in order to connect the MongoDB we have to call this function Mongoose dot connect as a first parameter for this function we will pass the URL for the database here we have the MongoDB protocol and here we have the localhost with default port number two seven zero one seven and here we have the database name in latest versions of Mongoose we have to pass the second option here use new or a passer as true and finally we have this callback function with a single parameter error first of all we will check whether we have any error or not if there is no error we will lock this message MongoDB connection succeeded if there is any error it will print that inside the look in order to run this DB dot J's file we have to add a request statement for this file inside the root file which is server dot J is fun so let's create the root file server dot J's inside that we will add this because statement for DB dot J is fine now inside this models folder we have to define the schema or structure of employee document for that I will create a new file here employee dot model dot J's of course first of all we need a request statement for Mongoose with this constant Mongoose after that we will create an object for employee schema so here is the object employee schema and here we have the constructor of schema star schema inside this object here we have to specify the structure of employ a document for employee document we have four fields full name email mobile and city so first of all we have the full name and it is of the type string and then we have email mobile and city all of them are of the type string now we have to register this employee schema inside Mongoose for that we can do this we will call this model function as a first parameter we will specify the name of the schema and here we have the schema object so in order to insert a new record into MongoDB we will call a save function from this schema object here by default it will use a collection with name employees because it will use the plural version of model name here with name employees which we have already created here employees so new record will be inserted into this default existing collection employees now we just need to add a request statement for this employee model inside this DB dot J is filed here so here we have done with connecting MongoDB and node.js application now it's time to start the Express server so I will add this request statement for Express with this constant Express now we just need to call this Express function with this variable app and in order to start this server we can call this listen function from this app variable as a force parameter we have the port number as the second parameter we have the callback function inside that we have this success message Express server started at port number 3000 in order to run this application we just need to execute this command here node then we have the root file which is server dot J's instead of running this node.js application with this node command I will prefer this one no more because then we change the source code when we change the source code while developing this application Nordmann will automatically restart the app in order to accommodate the new updates so it is a best practice to use Nordmann instead of not while developing the application in order to work with this norm on force therefore we have to install the corresponding package which is normal you can install the package with this command here I have already installed that in my system so we can run this command here so here we have the success message from both Express and MongoDB now let's navigate inside this port number localhost 3000 so here we are inside the project you can see this message cannot get because we don't have any route inside this node.js application here so let's create a route inside this application for that I will create a new folder here inside that I will create a new file employee controller dot J's inside this file we will deal with quite operations related to the employee first of all we have the request statement for express with the constant Express and now we need a router router is equal to is equal to Express dot router now we can create a new router here router dot gate function can be called inside that we have this default URL as a second parameter we have the request handler function with these parameters request and response from this function for now we will return a response with a string a spawn storge zone inside that I will pass a sample text finally we just need to export this router object from this controller here for that we can do this module dot expose is equal to router now let's configure routing for this employee controller inside this fort file server door Jas first of all I will add the request statement for employee controller here now in order to add a route for this employee controller we just need to do this we will call this use middle wave function here we have the base URI for this employee controller from this employee controller we have exported the router this line here will configure the routing for this no js' application let me save all of these modifications here then back to the application this Norman will automatically restart the application with new changes I will try to navigate the new route employee so here we have the response sample text which we have returned from this response here now from this route we have to return a form in order to insert or update an existing employee for that we will be using handlebars we have already installed handlebars inside this project now let's look how we can use handlebars in node.js applications so let's look how we can configure this node.js application for express handlebars first of all I will add the request statement for the path which is already the inside node.js application in order to work with path in node.js applications then we have the request statement for express handlebars with this constant now let's configure Express middleware for handlebars for that first of all I will set the view directly for this application by calling this set function as a first parameter we have views as a second parameter we have to pass the folder directory where we save the views for this application for that we will use the join function from path as a first parameter we have the reserved variable inside node.js application which is underscore underscore dir name which is B which is the base file directory path for this project in to that we have to join this views folder so we are going to create a new folder with named views inside that we will have handlebars view files now let's configure the Express engine for handlebars for that we can call this engine function as a first parameter we have HBS and here we have called this function from the Express handlebars inside that we have this object it may contain the configuration details for the handlebars first of all I will set the extension for handlebars view files it will be SBS then I will set the default view for this application default layout is equal to main layout so there will be a file main layout dot HBS inside that we have the overview of the application like HTML tag body tag head tag so-and-so so it will be a wrapper for the child views we will create the file in a B as the last option we have the directory for layouts inside a node.js application we may have more than one layout so here we have the layout directory for this application so inside the view folder we will create a new folder layout inside that we can create the layouts for the application finally we will set the view engine as HPS now let's create this folder views with this main layout door HBS file so here we have the folder views inside that we will have another photo layout inside that we will create this main layout view main layout dot HB this extension is provided here now inside this main layout we will have the HTML wrapper for the remaining child views so we will start with dog type as HTML then we have the HTML tag inside that we have the head tag inside that we will have the title title will be something like this nor J is Express DB correct after that we have the body tag now in handlebars in order to display a value of a variable we can use this double curly symbol and just type the variable name here since this is the main layout view for the application child view HTML should be rendered inside this body tag here in handlebars we have our third variable body inside that we have the HTML from the child views but this won't work as we expected because inside this body variable we will have the HTML string from the child views in order to render them as HTML we need to use 3 pair of curly braces for this application development will be using bootstrap and for icons they will use phone hours some icons so let me add those two style sheet here we have the bootstrap CDN reference and here we have the phone our some CDN reference I will use this BG info class from bootstrap in order to apply a background color for this body inside that we are going to use a div with class Rauf from bootstrap inside that I will use the grid system from bootstrap so here we have the deal with class called mt6 and we need an offset of three columns so we have the class offset md3 inside this day we will show this body from child views now for this day I want to apply background color margin and padding for that I will be using inline CSS with this style attribute because we don't have that much custom CSS rules for this application in order to create a separate style sheet so here we have done with main layout view now let's create a view with form for crud operations insert and update that we have to return from this request here - in order to create the view I will create a new folder here employee inside that we will have a view with name add or edit dot HPS inside the view first of all I will show a heading with h3 element and inside that we can show this variable view title so from this employee controller route we have to retain a value for this property view title that property value will be displayed inside this is three element after that we have the form element inside that first of all I will have the div with class form group this is from bootstrap first of all I will show the controls for full name first of all we have the label and here we have the textbox input with type text and here we have the bootstrap class form control and here we have the name for this input control which is important when we submit this form the data inside this input control will be will be returned inside a property with this name full name and finally we have the placeholder for full name like this we have to have a form group div for remaining properties like email city and mobile so here we have the div for email then after that I want to show both mobile and city in essing and for that I will use this David's class form draw all of these classes are from bootstrap first of all we have the mobile only difference is that here we have used bootstrap grid class called md6 so this line will be split into half inside the first half maybe showed me mobile controls and here we have the city controls okay in order to submit the form we need a submit button for that here we have the david form group inside that we have the submit button with class BTN and BTN info from bootstrap and here we have the button text submit inside this button I want to show a for our zone icon so I will add this I tagged here with class four and for database now let me save this view here so here we have designed a form in node.js with handlebars view engine now let's check how to return this view as a response for this request here for that we just need to do this response dot render function can be called as a first parameter we have to pass path of the view which is inside the employee folder inside that we have add or edit as a second parameter we have to pass an object containing properties which is to be rendered inside the view so right now we have a property view title that is to be passed from this object here view title is equal to insert employee now let me save all of these modifications here and then navigate inside this URL localhost 3000 forward slash employee boo so here we have the form for credit operations inside the node.js application now let's up me this form so that we can insert a new record inside this MongoDB collection employees before that I want to prevent this default behavior of an HTML form which is the autocomplete or predictions from previous posted form data I want to disable this feature for that we can set this attribute inside the form control here autocomplete I will set it as off now let's look how we can postpone that us in no J's applications with express for that we'll be using this action attribute here inside that we have to provide the URI to handle this post data so it will be here employee and I will set this method as post now we have to create a post route for this URL for that back to the employee controller then I'm going to create a new router here router dot post and with URI employee which is already there inside this base URL employee so we can just provide the forward slash here as a second parameter we need the function to handle the request so I will copy this function from here then paste instead of this I will have the console message console dot log then I will print the text hi now let me save all of these modifications then reload the page then submit the form now if you check the application console here you can see the hi message now what happens with the poster data from this form in order to show you that let me remove this action from here save then back to the application reload the page now if you submit this form we can see the form posted data inside the uri instead of passing these form data in URL parameters i want to have that inside this request body here for that we will be using the package body Passa and we can do inside this server dot JS file here now first of all we have to enclose the request statement for the body pass the package so here it is and we want to include these form that us inside the request parameter here for that we can do this we will use the use function from middleware and we have called this URL encoded function inside that we have this configuration extended as true now we want to convert that into a jason for that we will call the use function again with this format JSON now form data returned from this form here will be the inside the request object body attribute that I can show you here instead of this sample text here I will print request body here now let me save all of these modifications then back to the application then just reload this page let me enter some random text here now click on submit then back to the application so here we have the request body object containing details of the form here now let's look how we can insert the employer code in MongoDB for that we'll be creating a separate function here function insert record for the function we have two parameters request and response now we just need to call this function here insert record and into this function will be passing these parameters here now in order to insert a new record in MongoDB force therefore we have to create it an object of this employee schema inside this employee controller so first of all we have the request statement for Mongoose and here we have the variable employee in order to store the employees schema from Mongoose first of all we will create the object of employees Hima inside that we have to populate the form control values from request body object so here it is first of all we have the full name then we have email mobile and city now in order to save this record we just need to call this function say from this schema object inside that we will have a callback function with these parameters error and talk if there is no error while inserting the record we will be redirected to new route employee /list inside this route we will be listing all of the inserted employee record in a tablet if there is any error we will print that error object in console window now before testing the working of this post request here let me create a route for this list uri with a sample text response so it will be a gap request so let me copy this from here then here we have the function for request handling and the URI will be for slash employee for slash list inside this function we will return a JSON object response tall JSON function can be called inside that we will pass the string from list now let me save all of these modifications here then back to the application below the page let me fill this form with an employee details now in let's submit the form I hope we have successfully inserted the record because we already redirected to list URL and here we have the sample text from list now let's check inside the MongoDB we just need to click on this refresh button here so here we have the new employee record for Bruno Nash when we insert a new record into MongoDB it will automatically create this property underscore ID you can treat this field as a primary key for the records inside the collection before implementing rest of the crud cooperations I want to implement form validation inside this node J is an expressed application will be help of Momus schema as a first step towards the form violation first of all we have to update this mongoose model here employee i want to make this full name as required field and i want to check the correctness of email address format inside this property in order to make this full name as a required or mandatory field we just need to add this required attribute inside this object here here we have the required object and here we have the error message for the validation towards this full name if there is no value for full name we have to show this validation error message this field is required in order to check the correctness of email format inside this email field we have to apply custom validation inside the model so here we have the procedure first of all we have to call this function pass we are going to apply custom violation for email field and we have to call this validate function inside that we have this function with a single parameter Val that means value inside this field will be the inside this parameter and here we have the regular expression in order to verify the correctness of email format and in order to check the correctness we just need to call the test function from this regular expression object if there is an invalid email address we have to show this validation error message invalid email so that is what Nouveau violation inside the Mongoose model now we have to handle validation error message inside the employee controller here if there is any error related to validation this else block will be called details of valuation error will be there inside this error object in order to identify whether the error is due to the validation or not we can check the error object name attribute so this is what we do e r dot name attribute if it is equal to parameters for this function error object and body inside this error object we will have another property inside that we will have the validation errors for this field so I'm going to add trait through with the keys of the object so I will use this for I tration here filled in errors object inside this field we will have the name or field where we have a validation inside this for loop we will have a switch here this path means these fields here full name email mobile and city and here we have the first case if the validation is due to full name field we will save the validation error message inside the body for full name we will use this property full name error inside that we have to save the corresponding violation error message that we can retrieve from this message property it would be exactly similar to this one here okay now we have the email for email we will be using this email error object and here we have the final default case so inside this function we have saved properties valuation error message into the body object here now inside this else block here we just to return the updated view here for that we can just call this same view here let me copy this and pasting here along with this view title we have one more object which is employee inside that we will return the updated request body now we have to update this view add or edit HBS file here we have displayed these input controls without binding a property using handlebars as we have shown before when we submit this form this form controls value will be saved inside the request body so from this else block here we are returning that request body with updated validation error messages along with display validation error messages we have to show the values inside this input controls before posting this form for City we can do this here we have binded value property from this object here city from employee object we have returned the body as employee here like this we can bind values for remaining input controls also for mobile we can do this and email and full name text box also now we have to show the validation error message for full name and image for that I will be adding this deal with this bootstrap class text danger so that it will show the error message in a red color inside that we have binded this property full name error that we have populated inside this function here so when we have any error related to the full name it will be shown inside this div with red text now let me copy this and paste in here for email instead of this property we have email error now let me save all of these modifications here then reload this page now if I try to submit this form here here we have the validation error message both full name and email is invalid now let me try to submit this form with a random full name let's submit the form full name is valid but email is not valid if I try to fill this email with an invalid email will have the same invalid error message okay if there is any error due to validation those record will not be saved inside this employee's collection so here we have done well for violation in no js' with Express and Mongoose now it's time to show the insert or a course back to an HTML bootstrap double so let's look how we can get or retrieve insert of a course in node.js application with MongoDB so here we have already written an out in order to retain the list of employees which is here list in order to retrieve records from MongoDB we can call the find function from schema so here we have the employee schema we can call this find function from that inside that we have the call back function with these two parameters error and dogs inside these dogs we will have the all records from this collection employees currently we have only one single record inside this first of all we will check whether we have any error or not if there is no error we will return a view so we will call this render function from response and here we have the view we have not yet created this list dot HBS we have to create that inside this employee folder here as a second parameter we have to return these dogs for that here we have the object as a second parameter it will return these dogs inside this list property here if there is any error we will have the console message with the error object now let me remove this previous response JSON now we have to create this view list dot SBS inside this folder here so here we have the file list dot HBS inside the file we have this HTML table with few classes from bootstrap first of all we have the tea hat with a single draw inside that we have to show the column headers so first of all we have the full name and rest of the employee details like email mobile and city inside the tea body we have to show a course from this collection employees here that we have returned inside this object here list so let's look how we can render this object inside this list view here so we will be using this index here hash each we have the two curly braces and we have the pound symbol with each and here we have the property list inside that we have populated the records and here we have the each clause with this four slash inside this we have the TR element and here we have the TD element for each of the columns full name and rest of the columns email mobile and city along with these employee details I want to have an extra column for actions like edit and delete so here we have the empty header and inside this each loop I will add this TD element with a hangar element for each operations so here we have the first anchor element for Eric operation inside that we have this for our sum icon and here we have the second icon for delete operation now let me save all of these modifications here now let's now we get inside this route here hole slash employee for slash list so here we have render the HTML table in order to live across from this employees collection now I want to add h3 element for this table here so here we have the h3 element with text Employee List along with this header I want to have a button so that we can navigate into this form here so we just need to add this angle element here and that we have this phone our some icon with text create new and here we have the it's RF for this anger tag inside that we have the URL which returns a form for creation of new employee let me say this then we wrote this page if you click on this button here here we have the form for creating new employee along with the submit button I want to have a button so that we can see the employee lists so open corresponding view add or edit let's add an anger element for list so here it is we have the phone or some icon here with text view all and here we have the corresponding HR of in order to show the table employee /list let me save this then we know this if you click on this we have the Employee List now let's implement rest of the credit operations which are edit and delete in order to update an existing employee we just need to click on this pencil icon here then it will show this form populated with corresponding employee details then after making request changes we can update the employee record by submitting this form so a let's look how we can show the corresponding employee record when we click on this icon here so back to the IDE here first of all I will add a route in order to retrieve a specific employee given ID by ID I mean this ID which is created by the MongoDB so let's add the route here it will be similar to this get route here so let me copy this and paste in here for this route we will have a route parameter ID through this we can receive the MongoDB record ID in order to retrieve a specific record from MongoDB collection we can call this Mongoose function find by ID as a first parameter we have the ID underscore ID as a second parameter we have the callback function these two parameters error and dog if there is no error we have to return this add or edit with corresponding employee object for that we can call this render function inside that we have given the view name and here we have the object with title update employee then we have the corresponding employee document so inside this document along with these properties here we have this underscore ID so along with this input controls here I want to have a hidden field in order to store the underscore ID then only we can update the corresponding employee after submitting this form for update operation so I will add this input hidden field here inside that we have stored the value from corresponding property underscore ID let me save this file here then we have to update this h arif for this icon here so open list dot h PS and i will add this as our of attribute with corresponding URL so here we have the employee forward slash here we have the underscore ID for the corresponding employee let me save this then back to the application reload this page now if you click on this pencil icon here we have shown the corresponding view we have returned a form populated with corresponding employee details if you inspect this view here you should see because spawning input hidden field inside that we have the value which is same as that of this underscore ID here now in order to update this employee record we can make the required changes here then we just need to submit the form we have already written a route in order to handle this form submission so here is the route okay inside that we have to handle both insert and update operation in order to identify whether we have an insert or update operation we just need to check the value of hidden field which is underscore ID so we have to of this if clothes here then inside this else block here we can call the update function update record with the same parameter list and we copy this and pasting here now we just need to define this function update record so here we have the update record function with these two parameters because and responds in order to update a MongoDB record using Mongoose we just need to call this function find one and update inside that first therefore we have the filter condition in order to find the corresponding record for that we can use this condition underscore ID is equal to corresponding employee ID underscore ID as a second parameter we have to have the object with updated employee details and here we have the option I will tell you what we meant by this option U is equal to true as a last parameter we have the callback function with these two parameters error and dock with this option new is equal to true inside this dog variable we will have the updated details of the employee if it is equal to force you will have the old value of the record first of all we will check whether we have any error or not if there is no error it will return the list of employees with updated employee record details if there is any error for step four we will check whether we have any validation error or not then we will call this function handle validation error function which we have already written and we have to return the view with corresponding validation error messages if the error is not related to validation then we will show the general error object in console window let me save all of these modifications here back to the application then reload this page let me update this full name submit the form so here we have updated corresponding employee record so this is how we can update an existing employee now let's look how we can do the final crud operation which is delete so let's add one more route for delete operation here so here we have the get route for delete here we have the URL for the request delete then for slash then for slash call and ID which is the parameter inside this route and here we have the function for handling this request with parameters request and response in order to delete a document from employees collection we just need to call this function find by ID and remove from Mongoose library and here we have the underscore ID of the document and here we have the callback function with error and all parameters if there is no error during the operation it will return this updated list of employees if there is any error we will show the error object in console window now let's update the HR of attribute for this icon here so open list dot H PS so we can add the HR of attribute here employee for slash delete and here we have the parameter underscore ID since we have a delete operation it should be better if we can confirm the operation so I will add this on click even here with confirm function inside that we will confirm the operation with this question are you sure to delete this record or not if the user confirm the operation then only we will navigate this route here okay let me save all of these modifications here back to the application reload this page now let's click on this trash icon here here we have the confirm dialogue are you sure to delete this record click on OK so here we have successfully deleted the corresponding employee record so that's it guys in this video we have created a node J is expressed MongoDB application with crud operations insert update and delete you can now wrote this project source code from the link given below in video description if you found this video helpful thumbs up this video and for more hours and videos like this please be subscribed to this channel for affection please like and share this video with your friends and colleagues so that they can benefit from this have a nice day bye
Info
Channel: CodAffection
Views: 265,136
Rating: undefined out of 5
Keywords: node.js express mongodb crud, node.js express mongodb connection, table crud in node and express, handlebars in node js, handlebars node.js CRUD, how to install and use handlebars in node app, insert and get data in node and mongodb, express-handlebars in node.js, Node Express - Insert Update and Delete, Node & MongoDB CRUD, node.js express form submit, form validation in node.js, how to post form data in node.js express, connect mongodb from node.js, CodAffection
Id: voDummz1gO0
Channel Id: undefined
Length: 50min 50sec (3050 seconds)
Published: Thu Oct 25 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.