MongoDB Tutorial - CRUD app from scratch using Node.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys it's Pedro here from new quarter calm and in this video we're gonna give an overview of the crud application that we're gonna be building as well as going over what things you should be familiar with in order to follow along with this tutorial series so the technologies that you should be somewhat familiar with are nodejs and expressjs which we're going to be using for our server-side we're going to be using a database called MongoDB and for our client-side we're going to be using jQuery the fetch API and bootstrap and you should know a little bit about HTML and last but not least for our server-side and client-side we're going to be using a programming language called JavaScript so now let's actually take a look at the application that we're going to be building with in this tutorial series so this is going to be our to do application that we're going to be building it's a very simple interface so we just have a user input box where we're going to type or to do so let's say I want to type clean garage I can do so hit create and you can see that this gets stored now if I hit refresh you can see that the data persist so that means that we are saving it within our database if I want to edit this or something let's say clean room instead I could click Edit and you can see that we get updated with clean room hit refresh data persists and if I hit delete it deletes the to do and if I want to create multiple to do is I could say clean room clean house and etc and all this data will persist within our MongoDB database welcome to part 1 of building our crud application from scratch so essentially what we're gonna do in this tutorial is install our packages set up our Express application and connect to our MongoDB database so to get started I'm just going to file I'm gonna go to open folder I'm gonna right-click go to new we're gonna create a new folder so I'm just gonna call it MongoDB underscore crud let's select it and afterwards what I want to do now is let's open up the terminal and from here I'm just gonna type cos to clear the terminal and that's because there's a visual bug with Visual Studio code at the moment and what I want to do now is install our packages that our application is going to be dependent on so I'm going to type NPM in it and we're going to pass in the flag wife to get the default values and now I want to install the body parson module and the body parson module is going to be used the parse JSON between the client side and the server side next we're going to install Express and we're just going to use Express for routing next we're going to install MongoDB and this is just gonna be the MongoDB drivers and this is gonna help us connect to our database and last but not least we're gonna install the path module and we're gonna be using the path module just to serve a static HTML file to the user so now that we have our packages installed I'm just gonna go up here I'm gonna hit ctrl B to bring up the Explorer I'm gonna go to package JSON I'm just gonna change the main to app budget yes and this is just a personal preference I prefer app digest as opposed to index dot JSP this we're gonna create two files I'm gonna create my app by J's file and our second file that we're gonna create is gonna be called BBJ yes and this is where we're gonna actually connect to MongoDB now from here I want to code our app dot J's file first so I'm just gonna click here control B get rid of that Explorer and we could get rid of the terminal for now and what I want to do is start importing our modules that we just installed so I'm just going to say cons Express it's equal to prior Express and let's give a space here and next what we're going to do is bring in our body parts and module afterwards let's create an instance of our Express application so I'm just going to say Const a p-- is equal to it Express and let's call it now we're going to tell our Express application to use the body parson module and we're going to be parsing JSON data sent from the client side to the server side using the body parts module next let's require our path module after that let's bring in our database stuff so I'm just going to say cons VD is equal to require DB and last but not least we're going to have one more variable here and we're going to call it collection and we're going to call it a collection to do so we're going to have a database and that database is going to have a collection within it called to do and that's going to hold our R to dues so now let's head over to our dbj s file and now we're just going to import our MongoDB driver so I'm just going to say cons client is going to be equal to require MongoDB and we're going to require the client from it we're also going to require the object ID from the MongoDB module so I'm just going to say cons object ID it's going to be equal to require MongoDB dot object ID next let's give our database a name so I'm just going to say cons DB name is going to be equal to and I'm just gonna call it crud MongoDB after that we're gonna code our URL and this is basically the default location of where your MongoDB would be located on your local machine so I'm just going to type MongoDB localhost 27 0 17 and the last configuration that we're going to give our database is the options that we could pass in so I'm just gonna say options and we're going to be using the new URL parser let's set that to true so now let's actually give this a state so we're going to be using this D bjs file to actually create the connection between nodejs and our MongoDB server so now I'm just going to say Kant's state and the default state of this is going to be equal to null so this is going to signify that hey we don't have a database yet next let's actually write our connect method so I'm just going to say cons connect it's going to be equal and we're going to pass in a callback and we're just going to say the following if state dot DB so if there is a database connection we're just going to call it a callback if there isn't a database connection we're going to use the client to connect to the database and here we're going to if there's any errors if there's an error we're gonna pass it back to our callback if there's no error we're gonna set the state and then we're gonna call our callback alright so this is our connect method let's not forget to add the semicolon here and we got two more functions to code so let's get to it so the next function that we're gonna code is to get the primary key so I'm just gonna say cons get primary key and they're gonna pass in the ID of the document and all we're gonna do is return object ID and we're gonna pass in the ID that they passed in to us and this is going to return an object ID object which will be used to actually query the database by the primary key next let's actually create a method to actually get the database so we're just gonna say get DB and I'm just going to say return state dot DB so now let's actually expose all these functions that we create it so I'm just gonna say module that exports and I'm just gonna say get DB connect and get primary key method alright so now I'm just going to save this and now let's head back to our app dot JS file so now that we have all this set up let's actually connect to our database so now I'm just going to say DB connect and this is the function that we just created in our DB file we're going to pass in a callback and we're going to say if error we're going to console dot log unable to connect to database and we're going to terminate the application probably wrapped this within curly braces and if we were able to connect to the database successfully we're gonna say else app that listen and you could use whatever port that you want I'm just going to use port 3000 and we're going to pass in a callback and we're just gonna say connect it say database app listening on port 3000 so now if I was to save this let's put a semicolon here and then save it let's go open up a terminal type CLS again and a type node app and you can see that we got no error so that means we bypass this error statement and we executed our else statement so we're connected to database and our app is listening on port 3000 welcome to part 2 of building our crud application from scratch so in this tutorial we're going to be covering our server-side reapportion of our crud application so we're gonna code to get routes the first get route is actually going to send a static HTML file to the user and the second get route is actually going to query the database for order to Do's if an hour to do collection and it's going to return that to the user so let's actually get started encoding this so I'm just going to go down here I'm going to say apt-get and we're going to give it a path of forward slash give it this function and then when we get down here all we're gonna do is send a static HTML file so I'm just gonna say res dot send file and here's where our path module comes in handy join now this file doesn't exactly exist yet but we're going to be creating this within a future tutorial so now let's actually head on over to our second app and I'm just gonna call this app that yet and I'm gonna call this get to dues then here we're gonna pass in our function our request object our response object and within here I'm gonna say DB get DB now remember get DB is gonna return to us our database connection so now I'm just gonna say dot collection and we're gonna pass in the name of our collection and I'm going to call the method find and we want all the documents within our to-do collection but this is going to return to us a cursor and we don't want the cursor we want the actual document so I'm gonna call I met they called dot to array and then within here and this is going to take a callback function I'm just gonna say error documents and let's actually move this over a little bit and then within here we're just gonna say if there's an error we're just gonna console this out to the user but traditionally we want to send an error message back to the user but if there is no error what we're gonna do is first we're gonna print this out onto the console just to make sure that we're getting our documents back from the server and we're gonna say res dot JSON the documents alright so now let's actually test this out so I'm just gonna hit ctrl has to save let's bring up the terminal or a new terminal I'm gonna type cos node app let's bring up Google Chrome and then type local host for 3,000 and we called it get to Do's and you can see that we get back an empty array and that's because we don't have anything within our database so let's head back to visual studio code I'm gonna hit ctrl C cancel out of that let's start off the shell and now I'm just gonna go back up here control B let's find out what we named our database so we named it crud MongoDB so I'm just gonna say use crud MongoDB I'm gonna say DB dot and let's go back to app that yes and see what we named our collection to do I'm just gonna say to do dot insert and we're gonna insert a couple of to do so I'm just gonna say to do and I'm gonna say clean room so let's insert that and let's insert clean I don't know garage so let's insert that all right so let's cancel out of that note app let's wait for our Express application to boot up head over to Chrome hit refresh and you can see that r2 dues are being sent to the client side and that it is in JSON welcome to part three of building our crud application from scratch so in this tutorial we're going to be covering our server-side update portion of our crud application so to get started let's actually covert our route so I'm just gonna say app top clip and I'm gonna pass in borage / : ID now this is going to be our route pram and ID is gonna be the primary key of the document that we wish to update next we're gonna pass in our function so I'm just gonna say request and response now from here let's actually get the ID so I'm just gonna say cons to do ID is equal to request dot params by ID next what I want to do is actually get the user's input and that's gonna be found in the request that body the user is gonna be sending us JSON so I'm just gonna say Kant's user input is equal to request that body now from here let's actually connect to our database so I'm just gonna say DVD get DB then we're going to call our collection which is our to do collection now from here I'm going to call a function called find one and update and the first argument is going to be the query object so what do we want to find by so we're going to find by the ID so I'm just gonna pass in ID and I'm just going to pass in to do next what we want to do is pass in the document that we want to update with so I'm just gonna say set and I'm gonna say to do : user input dot to do next what I want to do is pass in an option and the option that I want is I want the return original to be set to false so I'm just gonna say return original and we're going to set that to false let me just move this here now from here we're gonna pass in our callback function so I'm just going to say error and we're gonna get the result so now let's scroll down here and from here we could test if there was any errors and I'm just gonna print it out onto the console but traditionally you will want to send something back to the user to let the user know that hey when we try to update the document that you want it we couldn't fulfill that request so now I'm just gonna say else so if everything went well we're gonna be sending that data back to the user in JSON format so I'm just gonna say result so now let's add a semicolon here and let's just double check this and all of this looks good so let's actually test this out so I'm going to open up the terminal and clear a terminal node app let's start up our application we're gonna go to postman and you can see here that I already have this set up so the URL is localhost port 3000 this is the ID of one of the documents that I have currently we're making a put request we're sending back JSON data here so you can see here and this is the data that we're sending back and we can make this whatever we want so let's just change this to clean something for tutorial right so this is going to be our to do and I'm gonna go here and make a request so I'm just gonna hit send and you can see that we get an error and right away I already know what's going on so when we pass then our to do and this is a string we want an object ID object so I'm gonna call DB dot get primary key we're gonna pass in the ID of this to do I'm gonna save this let's actually cancel this node app rerun our application we're gonna go to postman again and this time let's actually go over the response we got so it's the number that we found was equal to zero and that's because we didn't pass the right ID for the primary key so now if I send this this number should be 1 and updated existing should be equal to true so let's send it and you can see right here the number that we've updated is 1 this document did indeed exist within our database so it's true and you can see the values that we have the ID is still the same but we've updated it to clean something for our tutorial and if we hit another thing let's actually make sure that this update is working and we're going to say change to something else I'm going to hit send one more time and you can see the ID is the exact same thing but we've changed the to do to change to something else welcome to part 4 of building our credit application from scratch so in this tutorial we're going to be covering our server-side create portion of our crud application so to get started we're just going to code our route so I'm just gonna say app that post so we're going to be posting to do that we want to insert within our database so we're going to give it the path of forward slash and then we're just going to pass in our function the request object and the response object now from here what I want to end up doing is getting the users input the to do that the user wants to insert inside the database so i'm just gonna say cons user input and we're just going to say request that body so the client side the user is going to post json to us and that's going to be within the request stop body next let's actually get the database connection so I'm just gonna say DB get DB then from here I'm just gonna say collection pass in our to-do collection then I'm going to call a function insert one the first argument is going to be the document that we want to insert so I'm just gonna say user input and the second argument is going to be the callback function so I'm just going to say error and I'm going to say result now from here we're gonna test if there's any errors so I'm just gonna log it on to the console now in a production environment you would want to say something more than just logging it onto the console you'll probably want to display an error message to the user next I'm just gonna say else we're just gonna send it back to the user I'm just gonna pass it as JSON I'm gonna say result result and I'm gonna say document result dot ops index 0 now we're actually going to test this out so you actually see what's inside result and what's inside result ops so now I'm just gonna save this let's open up the terminal new terminal just gonna clear it I'm gonna say node app a startup server let's head over to postman and you can see that we have our localhost port 3000 here with the /url we're making a post request and this is a JSON object that we're sending back to the server so let's say that we want to post clean something so this is a to do that we want to insert within our to-do collection so now I'm just gonna hit Send and now you can see the response that we're getting back from the server so this is the result that we sent back and this is the document so result has a property of n so that's the number inserted and it says that it was ok so it was set to 1 so that means everything was inserted properly and number two is the document that we just inserted so you can see the to do here matches up here and it's given n primary key which is listed here so now let's actually see if this was saved so I'm gonna go back here let's make a get request remember what was our route we said get to dues I'm going to go to send and you can see right here that our to do clean something was inserted inside the database properly welcome to part five of building our credit application from scratch so in this tutorial we're going to be covering our server-side delete portion of our crud application so to get started let's actually code our route so I'm just gonna say app dot delete and the path that we're going to use is an Express / am so I'm just gonna say forward slash colon ID and this ID is gonna be died be the primary key of the to-do document that we want to delete from our database next we're gonna pass in our function our request object our response object now within here the first thing we need to do is get the ID so I'm just gonna say cons to do ID is equal to request dot params by ID next let's actually connect to our database so I'm just going to come down here and I say DB get DB then I'm gonna call it a collection method I'm gonna pass in our collection or to do collection then I'm going to call the function find one and delete so the first argument is the query object so we want to find this document by the ID so I'm just gonna say ID then I'm going to say DB get primary key and we're going to pass in our to-do ID the second argument is going to be the callback function so we're gonna get an error or we're gonna get the result so let me just fix this by adding the curly braces here error or result let's see what's happening here and this looks good so we have our error and result next we need to test to see whether or not there was an error so if there was an error that means we couldn't delete any so if there was an error what we want to do is actually print this out into the console you can also send some kind of warning back to the user that an error has occurred otherwise what we're gonna do is send JSON data back to the user so now I'm just gonna save this I'm gonna go to terminal new terminal let's clear this out node app and our application is running if I go to postmen you can see that I already have this running so we have our get to do these route here so I'm just going to send this again so you guys see that these are all the to do is within our MongoDB database so what I need is let's say I want to delete this to do inserting into the database so I'm just gonna copy this primary key we're gonna go back up here let's paste it so we have localhost port 3000 and the ID of the document that we want to delete I'm gonna go here we're gonna make a delete request and now if I hit Send let's see what we get back and this is the response that we're getting back from the server so number deleted is 1 and you can see the value of the document that we deleted and we get ok with the value of 1 so everything went fine so let's actually prove this out if I go back here get our - duze one more time hit send you can see that the document that was there is no longer there so this is pretty much the server side delete portion of our crud application welcome to part 6 of building our crud application from scratch so in this tutorial we're gonna be building our static HTML file that we're going to be serving to our user so in the previous tutorials we've created to get route 1 of them is to serve the static HTML file to the user and the second get route is to actually get auto to do is within our database so we're gonna be focusing on this route so to get started and gonna hit ctrl B to bring up the Explorer I'm gonna right-click new file and we're gonna create a new file called index.html well now I'm just gonna hit ctrl B again get rid of that and now I just want to head over to get bootstrap comm so we're gonna be using bootstrap for in order to build our HTML file so from here you can see that bootstrap actually gives us a starter template and this is going to include all the CSS that we need and the JavaScript that we need so I'm just gonna copy this let's head back over to Visual Studio code and now I'm just gonna paste this in here let's actually change the title so I'm just gonna change it to do read application and we're going to get rid of our h1 tag here so from here let's give it a container the first row is going to be where we input our to do user input the second row is going to be an unordered list which is going to be displaying our to do through the user you now from here let's head over back to bootstrap and we're gonna get our form so we're just going to head over to the search bar I'm going to type form group and I'm just gonna click that and this is going to take us here and this looks pretty good so we have our label and we have an input where the user can type his - duze to submit so I'm just going to copy this let's head back over to Visual Studio code and we're just going to paste this within here tidy this up a bit now we only need one of these so I'm just going to delete the second one now let's just scroll over to the right a bit and we're going to change some of this stuff so we're going to change the example label too to do and we're going to give an ID attribute to our input field so we're just going to change this from form group example input to to do user input and we're going to change the placeholder to say to do next we actually have to create a button so that the user can actually submit and we're going to give it a class of primary and that's actually called a button create now you could call this button post because that's the endpoint that we're gonna be hitting when we click this button but I'm just gonna call it create and that's gonna create our to do and before I forget let's actually change what the labels for so it's not foreign group example input is gonna be for our to do alright now from here this actually looks good so let's head over back to bootstrap and get our unordered list and we're going to be using to display our two do's through the user so from here let's go back to our search I'm going to type unordered and let's click the example they give us well this is an unordered list and you can see that has a bunch of list items here I'm just gonna copy this let's head back over to visual studio code from here let's just move over here and we're going to paste it in the second row so I'm just gonna tidy this up a bit let's give an ID attribute to our list group I'm just gonna say ID and I'm just gonna call it display because this is just gonna be displaying our two dues to the user and for right now I'm going to leave these list items here but we are going to be dynamically adding these list items to our unordered list all right so that's it for our HTML part let's actually start coding some JavaScript so I'm just going to come down here and we're going to add a script tag here two men thought ready so now let's actually get our HTML elements that we attached ID attributes to so I'm just going to say comps display and this is going to be the display for our two dues I'm going to say Const form and this is going to be the ID of our form and I'm going to say cons to do user input and this is going to be the to do that the user types in so first off I think I forgot to add to the forum so let me do that now our form we're going to give it an ID attribute and we're going to call it form and we're giving this ID attribute to the form because we want to prevent default so when the user actually submit we're going to prevent the default action that takes place because we want to make a restful call to our server API now let's go back down here so next we're going to code several helper functions so I'm just going to say kotts reset to dues input and this is going to reset the to do user input field create a function called build IDs and this is going to build unique IDs to give through our HTML elements and it's going to take in a to-do document and we're just going to return an object with our ID so I'm just gonna say edit ID and edit ID is going to be attached to our edit button so we can attach a click event to that edit button and you can see that we're taking advantage of the primary key that we get from our to do document to make it unique next we're going to code delete ID and delete ID is going to be attached through our delete buttons so we could attach a click event to our delete button next we're going to create a list item ID and this is going to be the ID of the Li element within our unordered list and the last ID that we're going to create is going to be called to do ID and this is going to be the ID of our to do now let's code a for function and this function is actually going to build the template the list item that we want to append to our unordered list I'm just gonna say cons build template and it's gonna take in two parameters I'm gonna pass an R to do and the IDs a string that will be appended so from here let's actually scroll up and let's get our Li element so I'm just going to copy one of these and realistically we could just delete this well now let's go back down let's paste this one within here let's delete this now let's give this li element an ID so we're just going to say ID going to be equal to IDs dot list item ID next let's give it a row you and we're going to make each columns of size four you so the first column is where we're actually going to be storing our to do so I'm just going to give it an attribute of ID we're just gonna say IDs thought to do ID and we don't want to actually display our to do to the user I'm just gonna say to do dot to do next let's go back to the last column so I'm just gonna give this an additional class and I'm just going to cause a text to the right so we want our buttons to be to the right of this and we're going to have two buttons within here so I'm just gonna say but in type II go it's the button going to give it a class of secondary and we're going to give it an attribute of the ID that we create it and the button is just gonna say now that we have our edit button let's copy this and now it's time to make our delete button so we're going to change this from secondary to the danger class and we're going to change IDs to delete ID and the name of our button is going to be called delete let me just take a look at this to make sure I typed out everything all right and this looks good and the last helper function that we're going to be coding is called display to do and that's actually going to display or to do this to the user I'm just gonna say cons display to do this and we're gonna pass in data and this data is going to be an array of two dues so I'm just gonna say data dot for each to do out of each of these get the IDS of each to do so I'm just going to say let IDs equal build IDs I'm going to pass in our to do next let's actually append each of these list items through our unordered list so I'm just gonna say display append and we're going to call the build template method that we just created and we're going to pass in our to-do and our IDs afterwards we're going to call our edit to do function now we haven't created this function yet and we'll do so in the next tutorials but basically the edit to do function and our delete to do function is going to add a click event to our edit button and our delete button I'm just going to say to do and we're going to pass in IDs that we do ID and IDs thought edit ID and likewise we're just gonna say delete to do and we're going to pass an R to do all right these dot list item ID and ID's thought delete ID so let's add ace we come in here and this is pretty much where I want to leave you guys at so we created our HTML file and we've added all our helper functions that's gonna help display our data to the user welcome to part 7 of building our crud application from scratch so in this tutorial what we're gonna do is display our two dues to the user by making an HTTP GET request using the fetch API so if you remember from our previous tutorials we coded this get route does it get to dues and the job of our get to do is route is to actually get all our to dues from the database and return it and it's going to be returned within an array well now if I head over to our index.html what we're going to do is have the fetch API call this get to do is route I'm just going to go here and I'm going to create a function called get to do so I'm just gonna say cons yet to do and within here we could use the fetch API so I'm just gonna say fetch and it's going to be the URL or the endpoint that we want to hit so I'm just gonna say get to do the next argument is going to be the type of method that we want to use so we coded a get method next we could call it a den method and we're gonna get a response back from the server and I'm just gonna say return response JSON and this is gonna parse the JSON for us but this is going to return a promise and when you return a promise we could chain that promise I'm just gonna call it done method once again that's in our data and now here I'm just gonna console dot log to data and we're gonna pass this data this array of two dues to our helper method so I'm just gonna call it display two dues and we're gonna pass in our data now let's just add this semicolon here and let's actually invoke or get to do is method and now if I was to save this and let's open up a terminal and I'm just gonna clear it I'm gonna say node app let's start up the server so now let's open up our browser so now from here let's just type localhost port 3000 and you can see that our two duties are being loaded so let's bring up the developer tools so I'm just gonna hit f12 and we go to our console you can see the array that the server is sending us so if we open that up you can see our two Do's we have our primary key and to do now let's head over back to visual studio code to see how this is working so now if we come back here we can see that our array of two dues is being passed into our display to do this let's take a look at what display to do is is doing so display to do is actually taking an array of two dues it's building its unique IDs or are HTML elements and it's calling build template now build template is going to be used to build our list element that we're going to add to the unordered list so you can see that happening here once we build this HTML template we're returning it and it is going to be appended to our unordered list but that's pretty much how we are displaying our - dues to the user looking apart eighth of building our crud application from scratch on this tutorial we're gonna be making an HTTP POST request using the fetch API so if you remember from our previous tutorial we coded this post route and we just gave it forward slash it's gonna take data from the users we're gonna have to post data back via the body and you can see that it returns two things the result whether or not we successfully deleted the item or not and it returns back the inserted document that we just inserted well let's head over to index that HTML and let's actually go with this so from here we're gonna use our form that we have up here so this is our form and what we want to do is prevent the default form submission so we're gonna come down here and I'm just gonna say form dot submit and this is gonna take in a function and it's gonna have an event and what we're going to do is say e dot prevent default from occurring next we're gonna call it a fetch API so I'm just gonna say fetch we're going to use our endpoint of forward slash the next argument is going to be our options so the first option is we're posting data back to the server I'm just gonna say posts our second property is going to be the body what we're sending back to the database so i'm just gonna say json dot stringify and we're going to send back our to do so we're just going to use to do use our input and we're going to get the value that our input field has at the moment let me just move this over here and the last option is we're gonna have to pass in headers and what a header is is it tells the server what kind of content you're sending back to it so I'm just gonna say content type and we're sending back JSON now from here let's call it the den method so I'm just gonna say den we're gonna get our response back from the server we're gonna return that response that JSON which is going to be a promise that parses the data for us we're just going to call it then on the promise that's being returned and we're going to get our data back next we're going to have to test to see whether or not we successfully inserted the document I'm just going to say if the data result okay is equal to 1 and data dot result n is equal to 1 that means our to do was successfully insert it into our database I'm just going to say let IDs equal to build IDs and we're going to pass in our document next we're going to call it the display method so this is going to append a new list through our unordered list and last but not least we're going to have to attach our click events through our edit button so I'm just going to call edit to do which is a function we haven't created yet and we're going to pass in our to do our to do ID and the ID of our button we're going to have the attach event to our delete button as well SNR to do the list item ID and the reason we're passing in the list item ID is because we need the ID of the list that we want to delete and we're gonna pass in the ID of the delete button so for now I'm just gonna comment these two out because they don't exist at the moment right now we have displayed pen and this looks good to me and last but not least once this successfully happens what we want to do is actually reset our to do is input so let's actually test this out so I'm just gonna hit ctrl shift and backtick let's clear the terminal node app let's open up a browser so now let's actually test this out so I'm just gonna come up here and testing post I'm going to click the create button and you can see that our to-do was successfully posted through the database so I'm just going to hit refresh to see if it actually worked and you can see that our data is persisting so that's the basics of using the fetch API to post to the server and welcome to part 9 of building our crud application from scratch so on this tutorial we're going to be making a HTTP delete request using the fetch API so in the previous tutorials you can see that we coded our App table delete route and it's using a route parameter we get that ID of the to do that we want to delete here and then here we call the find one and delete function we pass in our primary key Ord ID and what we end up getting is the result whether or not we successfully deleted the to-do document within our collection now let's actually head over to index.html and let's actually code our delete to do function well now from here I'm just gonna say cons delete to do and it's going to take in three parameters it's going to take a to do is going to take the list item ID and it's going to take the delete ID now to do is the document that we want to delete list item ID is the ID of the list element within our unordered list that we want to delete and the delete ID is the ID that we've given to our delete button now let's actually code this out first we need to get our delete button so I'm just going to say let delete button is equal to this next let's actually add a click event to our delete button so I'm just gonna come down here leet button dot click and we're gonna pass in our click Handler and within here let's actually call our delete route using the fetch API so I'm just gonna say fetch and we're going to pass in our route next let's actually pass options so we're actually making a delete request so I'm just gonna say method and we're gonna pass in delete now from here let's call it a den method to actually execute this fetch function I'm gonna say then what we're going to end up getting back is the response from the server next we're going to return that response and we're going to call the JSON method on it and this is going to return to us a promise so now we could promise chain I'm just going to call it then again and we should get back our data that is fully parsed now from here let's actually test to see whether or not we successfully deleted the to do I'm just gonna say if data okay is equal to one that means we successfully deleted our to do so now we need to remove the Li element from our unordered list so how do we do that well we have our list ID and we're just gonna call the method remove so this is going to remove our li element from our unordered list well that's actually add a semicolon here all right now from here let's go down to our display to do this and alright so we already have the AR delete to do uncomment it so if this should work well now I'm just gonna save this let's go back to app dot J yes let's actually open up our terminal and from here let's actually run our application note app and you can see that our application is up and running and now let's head over to our web browser and let's actually test this out so from here you can see our to-do application is up and running I'm just gonna refresh this just a triple-check and what we want to do is actually hit our delete button to see other work so I'm just gonna hit the leap and you see that testing post is gone if I hit delete again you can see cleanroom is gone and if I hit refresh you can see that this does persist onto the database and that those two do's are actually deleted from our database and welcome to part 10 of building our crud application from scratch so in this tutorial we're going to be making a HTTP put request using the fetch API so in the previous tutorial we coded our app that put route so this is the endpoint that we're going to hit we're using route params and this is going to be the ID of the document that we want to edit we're also sending data back via the body as you can see here and this is going to be the data that we want to update with right here you can see that we are finding by the ID so this gets the document that we want update this is updating the document here and if you scroll here you can see that we're sending back the result whether or not we were successfully able to update the document or not so now let's actually head over to our index.html file and actually code this I'm just gonna come down here and I'm gonna call it the function edit to do and it's going to take in three parameters first is going to be the to do second is going to be the to do ID and third is going to be the edit ID the first parameter to do is obviously the document that we want to edit to do ID is the ID of the to do and edit ID is the ID of the button now let's just come down here and now from here what I want to do is actually get our button and once we get our button what we want to do is attach a click event to it so I'm just gonna say edit button but click SN R callback and from here we can use the fetch API to hit our endpoint in our server I'm just going to say fetch and the endpoint is forward slash and the ID of the - dude that we want to edit the second argument is going to be our options so we're just going to say method and we're going to set that to a put request we're gonna set our headers and our headers are going to be set and they're going to tell our server that we're sending back JSON all right now from here let's set up one more property and it's gonna be our body so what we're gonna do is actually send what we want to update our document with i'm just gonna say json stringify and this is going to convert our JavaScript object into JSON for us and I'm just gonna say to do and we're going to get the users input well now that we have our options set up let's call it a den method to execute this fetch request here we're going to get our response from the server now we're going to return that response and we're going to call a function called JSON now this response that JSON is going to return a promise so I'm just going to go down here and I'm going to call it then and it's going to give us our parsed data back so now I'm just going to test to see whether or not we successfully updated our to do I'm just gonna say if data dot okay is equal to one that means that everything went okay now what I need to do is actually get R to do element so I'm just gonna say let to do index equal equal our to do ID next what I want to do is actually set our data so I'm just gonna say to do index.html is going to be set to the data that we just got back from the server now what I want to do is reset the users input so I'm just going to call the reset to do input function I'm just gonna scroll down just to check to see if we have our edit to do is being called and it's being called here alright so let's actually test this out in our web browser to see if it actually works I'm just going to save this I'm going to open up the terminal I'm gonna clear it node app head over to our browser Oh from here you can see that we have our application running just gonna hit refresh just to make sure and right here I'm just going to type whatever and now I'm going to hit edit and you can see that our to-do document was updated so just gonna hit refresh again let's see if it persists to the database and you can see that it is persisting and let's try one more just to make sure and you can see that it is indeed working welcome to part 11 of building our crud application from scratch so in this tutorial we're going to be doing some user input validation using joy so to get started let's actually install joy I'm just going to come down here NPM install Juhi now that we have our joy package installed let's just lien cluded it within our application so I'm just gonna come up here I'm gonna say Kant's joy is equal to require joy now from here let's actually develop a schema for a to-do document now if you don't know what a schema is it's basically a blueprint that an object has to follow so let's come down here and let's define our schema I'm just gonna say Kant's schema is equal to joy not object and now we want to define our keys now from here we're gonna give our properties and the type that they should be so for example we only have really one object within this tutorial and that's what to do so here I have a to do and the type that this should be is of type string so I'm just gonna say joy doc string and we're going to make it required so when the user input is to do this schema is gonna make sure that it's a string and that it's not empty so required means that if the user tries to submit a to-do that's empty we're gonna get an error if the user tries to submit a number instead of a string we're gonna get an error but that's how we're gonna validate user input so I'm just gonna end a semicolon here now let's take a look at our routes so what we want to do is validate anything we get back from the user so for example this route parameter here we would want to validate now this is not a to do object but this is the primary key but anything the user sends back to us you would want the validate so this request body we would also want to validate for and if we take a look here request body here request params here and that's pretty much it so for this tutorial I'm gonna do one example with you guys and you guys could pretty much figure out how to do the rest yourselves so I'm gonna choose to do our poster out but we're going to validate the user input sent by the body here I'm gonna call joy dot validate and validate is a method which is going to take three arguments the first argument is the object that you want to validate so we're passing in user input the second argument is the schema or the blueprint that you want to check against user input but we're just going to pass in our schema we just created and the third argument is our callback function and we get the error and we get the result now from here I'm going to say if there's an error what I want to do is we're going to create an error so I'm just gonna say Const error is equal to new error and we're gonna pass in the message that we want to display to the user I'm just gonna say invalid input next I'm gonna give this error a HTTP status code so I'm just gonna say error dot status and I'm just gonna set that to 400 next what I want to do is call the next method and that's because we're gonna have a middleware handle our errors I'm just gonna say next and we're going to pass in the error we just created so from here since we're using a a middleware we have to pass in next as a parameter so now from here let's code our else statement so if there's no errors with the users input what do we want to do so I'm just gonna say else and what we want to do is actually get our database I'm just gonna cut this out I'm gonna paste this in with in here and now here what we can do is some more error handling so right here I could come here instead of just printing this out to the console what I could do is exactly what I did a book I could copy this just paste this in here and instead of saying invalid input I could say something like this I could say failed to insert to do document and we're gonna leave the status coat the same and we're gonna call our middleware error handle here so from here we could go down to this else statement and we're gonna have to pass in a couple more things and this is just to make it easier for the front end so for example we are gonna pass in a message and this message is going to be displayed if we successfully insert it into the database so i'm just gonna say successfully insert it to do the next thing that we're going to pass in is an error property and we're going to set that to null so that means that there was no errors and we're gonna be using this to test and our front end so this looks good to me well now let's code our custom error handler our custom middleware I'm just gonna go down here and [Music] let's put it here well now I'm just going to say app thought use and we're going to pass in our error object next is going to be the request object the response object and the next object now here what I could do is actually send a response back from the server well now I'm just going to say res dot status and we're going to set the status to the error status that we set in our post route I'm just gonna say error dot status next I'm going to call it the JSON method so we're going to be sending this back to the user and from here I'm going to pass in an error property and this is going to be an object and it's going to have property a message and we're going to pass in our error message I'm just going to say error message all right now from here what I want to do is let's head over to bootstrap and let's get our alert that we're gonna be using to display to the user so let's go to bootstrap and get our alert that we're going to be using to display to the user whether or not our post request was successful or not so from here I'm just gonna go to search I'm going to type alert and you can see that we have a bunch of alerts here what I want to do is get our success alert and we're gonna be using this to display when we successfully posted something and I want to use the danger alert when we get an error I'm just gonna come down here and we only need one of these so I'm just gonna pick up the danger one I'm gonna copy this and I'm just gonna head back to visual studio code now from here I'm just gonna save our app dot J's file and I'll go to index.html and what I want to do is actually put this underneath our display though right here I'm just gonna paste this here and let's actually steal some code from our display I'm just going to add a break here just to give us some space I'm going to copy this I'm going to paste this here [Applause] want to do is get rid of this unordered list and we're gonna be putting our alerts here so I'm just going to copy this taste this in here let's tidy this up a bit and what I want to do is actually get rid of this and let's add an ID attribute of message from here let's actually scroll down to our script tag and what we want to do is actually get our message that we just gave an ID for I'm just gonna say con some message and we're gonna be getting our ID now from here I'm just gonna say message God hide because I don't want to show it yet next thing I want to do is create a helper function so I'm just gonna come down here just gonna say can't display message and the first parameter is gonna be a flag whether or not we should display the success alert or the danger alert the second argument is going to be the message that we want to display now from here I'm just gonna say if flag so if this is true and let's actually make a comment so if we had a successful post what we want to do is I'm going to say message dot remove class and we're going to remove the alert - danger class and I'm just gonna copy this paste this and we're going to change this to add class and we're gonna add a success alert next I'm going to say message dot HTML and we're going to pass in the message that we want to display and I'm gonna say message dot show actually display our alert so now from here since we have a success we need a else statement to display to failure so I'm just gonna say else and now I'm just going to copy all of this and pretty much we're gonna do two opposite so instead of saying remove danger class we're going to remove the success class and here we're going to be adding the danger class and these two lines of code are gonna be the same so actually by coding this I actually forgot to remove this part from our HTML so yeah so let's get rid of this and we have our alert and we have our message okay so that looks good so now let's actually go down to our post host and from here what we're going to do is actually wrap this if statement so I'm just going to come up here I'm going to say if and we're going to use the not symbol so data dot error so there are no errors what we want to do is execute this block of code we want to do is actually get our alert to display I'm just gonna say display message and we're gonna set this to true because that means that everything went okay and then we're gonna pass in the message that we want to display I'm just gonna say dated on message and from here I'm gonna make an L statement I'm just gonna copy this paste this here instead of true we're gonna say false and let's display our error message so I'm just gonna say data dot error message now from here let's actually go back down we do have to reset our to do input so I'm just going to call it that so now let me just save this and let's actually test this out so I'm just going to come down here node app and let's see what we got wrong oh joy dot string dot require this require is not a function let's go back to our app dot J s probably not required it's probably required well now let's save this let's clear the terminal node app all right so now our application is up and running and now let's actually test this in the browser now we have our to-do application up and running so now if I was type of string and hit create you see that we guess successfully inserted to do and if I was to have an empty string and hit create you can see that nothing's updating so that means that we made it error so now let's head back to visual studio code so from here let's just go back to our index that HTML file let's actually take a look at this so we have our if statement here and that's pretty much the reason because this if block is only supposed to be wrapped around this if condition but we also have our else block here well this code isn't being executed so let's actually copy this let's get that out of there and from here you just paste that here two resets here now let's say this for now let's head back to the browser I'm just going to hit refresh to reload the page and we could test this one more time so we inserted our to do okay now we have a blank user input it create and you can see that we get a warning invalid input that's pretty much how you can validate user input using joy or our to do application
Info
Channel: freeCodeCamp.org
Views: 136,563
Rating: undefined out of 5
Keywords: mongodb, mongo, mongodb tutorial, mongodb course, mongodb tutorial for beginners, Node.js, Express.js, jQuery, Bootstrap, fetch api, crud, todo, document database, mongodb crud, mongodb crud app, nosql
Id: CyTWPr_WwdI
Channel Id: undefined
Length: 72min 41sec (4361 seconds)
Published: Fri Dec 28 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.