Learn The MERN Stack - Express & MongoDB Rest API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign hey what's going on guys so I want this channel to be a resource for anybody that wants to learn web development that can start anywhere including just HTML CSS and then kind of go through and learn different Technologies and Frameworks and I basically want to have all up-to-date content because right now some of my crash courses are out of date I'm working on you know updating those but I wanted to do something with the merge stack because that's really popular with with my audience and instead of just doing everything in one video I figured we could do a single project and spread it across three or four videos and work on something different in each video so for instance in this video we're going to build a rest API with Express which is a back-end node.js framework and mongodb for our database as well as Mongoose which we'll use to connect and interact with mongodb so that's what we're going to do in this video and then in the next one I want to add authentication which is some something that's very important in in building apis so we'll be able to create a login endpoint a register endpoint and we'll be able to get a Json web token once we authenticate and then we can use that token to access protected routes all right so after that on the in the third video we'll start on the front end we'll start on the user interface and we'll have a register form login form and basically we'll have a dashboard where we have goals so the the main resource in this project is going to be goals and that's what our rest API is going to be we can create read update and delete goals all right and in the front end I also want to use Redux that's something that I haven't really done in a while on my channel we're also going to use Redux toolkit now this this is basically just a smaller version of my support ticket application from the react front to back 2022 course so if you did take that course and you did that project this is very similar it's just a little smaller uh same authentication and everything it's just we don't have the support ticket side of it we're doing goals instead all right so I think that this will give you a really good foundation in the Marin stack and and how everything works and I would definitely recommend that you you follow along code along with me and really just immerse yourself into the learning and if if you don't understand something pause it look at some documentation some other resources and uh and just really get into it I think that's the best way to do anything all right so that's it let's get into it and start on our rest API okay so before we get into the code I just want to go over what a rest API is and how it works so this is an image that I found from Network op.co.uk and I like this because it has a lot of information in one small image so basically we have our client which is going to be ultimately our react application and that's where all the UI stuff goes all of our components our state with Redux everything is on the client and then the back end or the server we're going to build with Express which is a node.js backend framework and this will be our API so we need these two to communicate and we do that with a rest API and that includes basically a bunch of HTTP requests and the operations that we want to do here are are called crud create read update and delete now in this case if you look at these endpoints API slash devices this example they're using devices as a resource but ours will be goals so the endpoints will be API slash goals Now to create a goal or a device in this case you would make an HTTP post request post is the method okay so you can see these have different methods so to create something or to post to the server you use a post request and then the the endpoint is going to be slash API slash devices or goals in our case and you also send a payload of data because if you're creating something obviously you're going to send some data with it and that goes in the HTTP body which we'll talk about in a little bit so this gets back a 201 status code from the server which means everything went okay and something was created now to read devices in this case we would make a get request so get is for reading data and it would be just the endpoint API slash devices and you'll see that these are these two endpoints are the same but they do have different methods okay and then you just get back of 200 which is everything's okay and then to update you'd make a put request and this time you'd include the ID in the actual endpoint in the URL because you need to know which which device or which goal in our case is being updated all right you get a 200 response back and then same thing with delete so you make a delete request to API slash devices slash and then whatever the ID is and you get a 200 response back so basically in this video our goal is to create an API just like this for goals and we're going to be using Express mongodb for our database and Mongoose to to connect and interact with our database now obviously we don't have a front end to work with so while we build our API we're going to be using a tool called Postman which is an excellent tool excellent HTTP client if you want to use something different if you know something that is similar to postman and you want to use that that's absolutely fine but I'll be using using Postman and then mongodb is what we're using for our database we're going to use mongodb Atlas which is a cloud database so we don't actually have to install it on our system or anything like that all right so many times I'll start with creating the database but I think what I want to do first is just get our API up and running create our routes and then we'll start to set up our our Cloud database and then connect to it at our models and all that so the first thing we're going to do is create our project folder so I'm going to just open up my terminal and we're going to go into wherever you want to create this I have a folder called Dev and then I'm going to make a directory so mkdir and I'm going to call this mer Dash tutorial and of course you can call it whatever you'd like and you can create this through your your graphical user interface if you want and then I'm going to CD into the uh not make there I'm going to CD into the mern tutorial folder and then from there I'm just going to run vs code with code Dot all right so we should just have an empty folder now this is going to be the route to our full stack application so I'm first going to create a folder in here called back end and this is where all of our routes our models controllers everything is going to go in this folder so I'm going to create in that folder a file called server.js which is the entry point to our server and just for now I'm just going to console log and I don't know we'll just do hello world and we'll save that for now so in the root here not in the back end folder but in the root is where all of our our back end dependencies are going to go so Express and all that will be in a folder called node modules in the root so I'm actually going to open up my terminal my integrated terminal here you don't have to use this you can use your regular terminal if you want but I'm going to go ahead and run npm and knit and we'll just go through this so version that's fine description I'll say goal goal Setter app for YouTube say for YouTube tutorial I guess and then I'm going to use server.js as the entry point and let's see keywords we don't need that you can put your own name in here if you want and I'm going to use an MIT license so that will create a package.json in the root and then before we install any dependencies I'm going to create another file in the root called dot git ignore because I do want to initialize a git repository but I don't want the node modules folder to go in or the dot EnV file so I'm going to add both of those to this git ignore all right and then we can install our dependencies so from the root we want to do npm install and we're going to install Express we're going to install something called dot EnV so that we can have environment variables and then Mongoose and then there's a utility called colors that I like to use so we can use colors in the console and I think that's all we need for now there's other stuff that we need later but I think yeah I'm pretty sure that's that's all we need for this video now as a Dev dependency I'm going to npm install Dash uppercase D and then node mon which is a tool that will constantly watch our server.js file so we don't have to keep restarting it so now what we can do is go into our package.json and you should see your dependencies and node one as a Dev dependency and we're going to add a script here called start and then let's get rid of this and we want this to run with node.js we want to run our backend slash server.js file and then what I'll do is copy this down and we also want to run node mon and the script for this will be called server all right so we should be able to run npm run server for node mod to run our server.js file so let's try that out we'll come down here we'll say npm run server and there we go so it spits out hello world and it's just constantly watching for changes I'm going to go ahead and just stop that with command or control C and now we have that set up now I would recommend that you create a git repository so I'm going to go ahead and get a knit and then we'll do get add all and then git commit M and I'll just say initial commit and we're probably going to deploy this to Heroku so we do use git to do that so I would recommend doing that and just making commits As you move along so as far as the front end we're going to do that later on I just want to create our backend API first so we're not even going to create a front-end folder just yet now we have our server.js like I said this is the entry point so let's get rid of this and we're going to go ahead and bring in Express which is our back end web framework so it's bring that in and then I'm also going to bring in dot EnV so that we can have environment variables don't Dot and V and set that to require dot EnV and then we just want to call a function called config so we just do dot config like that and that will allow us to have a DOT EnV file with our variables in it and then for the for the port I'm just going to create a variable I'll just put 5000 in it for now it's the port we want our server to run on now we need to initialize Express so we're going to create a variable called app set that to express and then with that app object we can call listen which takes in a port number so our Port variable and then you can also have a second argument with a function and I just want to do a console log with some backticks and we'll say server started on Port and then the port number all right so just having this we should be able to run npm run server and we should see Server started on Port 5000 but I'm going to cut this off because I want this port number to actually be in an environment variable so in the root here not in the back end folder but in the root we're going to create a DOT EnV folder file sorry and I'm going to put in here a couple things we'll have our node environment and we're going to set that to development and then we're also going to set our port and for now I'm going to set it to 8 000. so now here where we set our Port I'm going to go in front of the 5000 here and say process Dot env.port and what that does is it allows me to access that Port variable in my DOT envn and we can use this anywhere in our server but I'm going to also just add or 5000 if this isn't found for some reason so now if we go ahead and run npm run server again we should see it on 8000 because it's reading it from the port here however I'm going to change it back to 5000 here because that's what I ultimately what I wanted to run on now whenever you change or add something to the dot EnV you do have to restart your server other than that we can run it now and we should be all set even if you want to install other packages and so on so to create a route I'm actually going to open up where is it where the hell's Postman I'm going to open up Postman and let's close this up so just download it from postman.com or you can use a different HTTP client you could even use your browser right now because it's only a get request but basically we open a tab and we can make any type of request any method we want I'm going to choose get and then to access our server we can do localhost it's on Port 5000 so colon 5000 and then let's say we want to do slash API slash goals so ultimately that's going to get our goals right now we just get a 404 not found response and it just sends an HTML page but this is the route that I want to create to get all of our goals ultimately from our database so we could go in here and say app.get because get is the request we want to listen for and then the end point would be slash API slash goals and then we just have a second argument of a function that takes in a request response variable and then to respond we could do just res dot send and we could pass a string in here and just say we'll say get get goals because ultimately that's what this is going to do so now if I send this we now get a 200 status which is okay and then we have a string of get goals now usually you're going to return Json so for the most part we would do dot Json and pass in here a Json object or Json or an array and we can say like message and we'll set that to a string of get goals all right so we'll send that and now you can see we get a 200 response we get this and then if we look in our headers the content type should be application slash Json all right and even though we didn't add like you know double quotes on the key it just gets uh parsed into Json with the double quotes so you can set the status yourself now this does give us a 200 as you saw but I still usually like to do status and set it to 200 and then just add dot Json and that will give us the same result all right now you're probably not going to want to have all your routes in this one server.js file you really want to clean your your folder structure up or else it's going to get really messy so in the back end I'm going to create a folder called routes and then in that I'm going to have a file called goal routes go routes.js so basically each resource in your API will have its own route folder route file sorry now to use the express router we're going to first bring an Express into this file so let's require Express and then we can create a variable called router and we can set that to express.router uppercase r and then you just need to export this so we're going to say module exports and set that to router okay and if this syntax if you've never seen this before this is common JS module syntax which is different from you know when you would import Express or whatever that's es2015 syntax and that's what we use in the front end with react and View and so on you can use that syntax in node.js but there's some additional steps you need to take at least at this time so I usually stick to the common Js so to create a row what we can do is copy that or cut this and then put that in here right above where we export and just change the app to router now this API goals I want to have this if if we hit this from the front end I want it to direct to this file so I'm actually going to just make this a slash and then what we can do is under where we initialized express we can do app.use and we can say slash API slash goals and as a second argument we can require the file that we want that to pertain to which is going to be routes and then goal routes so now if I hit API slash goals it's going to look into this file here and all I need is a slash because the API slash goals was already specified so if I make a get request to API slash goals we now get the same response and we were able to move that to this file all right now I'm going to have a couple other routes here so let's copy that and we're going to have four because we want to be able to get we want to be able to create a goal so that'll be a post request and we'll just leave this AS Slash which ultimately is going to be slash API slash goals and a post request will create a goal so I'm just going to change this to or let's say set goal okay and then down here so to update it's going to be a put request all right so we're going to say put and then we do need to include the ID remember that image that I showed you this right here to make a you make a put request and then it's going to have slash ID same with a delete request so what we do is put colon slash ID here and that's going to be our param now you can access this within your route so I'm going to actually use backticks here instead of quotes so I can include a variable and we'll say update let's say update go and then we can use this syntax to add a variable and I can take that request object so request.params and then dot ID because that's the param that I want to get okay and then we'll do the same for the delete so I'm going to just copy this and then this is going to be a delete request and we'll test these routes in a minute and then let's see we'll paste that in and we'll just change that to delete and we want to make sure that we add a colon ID here as well because remember it has to include the ID so now let's come over and test these routes out so get request that works post request is going to be the API slash goals so you can see we get a 200 and it says set goal if we make a put request to goals slash and then whatever some number which would be the goal ID we get update goal and then that number if I do a delete request to that same endpoint we get delete goal and then that number all right so now we have all of our routes set up they're not doing anything except just spitting out you know a message but they are set up now we could proceed to add our functionality in the body of these callback functions but it's much better practice to actually create a controller and have your functions there so in the backend folder let's create a controller our controllers folder and then we're going to go ahead and add here goal controller.js and then here we can just create some functions so for instance we want to get goals function and it's going to take in request response all right and then we'll have the same you know same thing just respond with uh status and message now to use this I'm going to export it down here so I'm going to say module.exports and set that to an object and then we're going to pass in the get goals function now in our routes we can bring that in from the controller so let's say const and that's going to be from require and then we want to go let's see out of the routes into controllers and then goal controller and what we want to get is the get goals function now this right here the get request to slash which is slash API slash goals I'm going to replace this whole function here with get goals all right now that should still work if I make a get request to API slash goals you'll see that it does the same thing and now I have that functionality moved to my controller file now I want to do this with the rest of these as well so let's uh actually before I copy this one thing I want to do and if you guys have ever taken a node.js course for me you know that when I create my my controller functions I like to add a couple things in the comments I like to add a description of what this does so we'll say get goals and ultimately this is going to get all goals but after we add authentication it'll only get a specific user goal all right now I'm going to add the route so let's say route and I also add the method here so it'll be a get request to API slash goals and then I also like to put the access so it can be public or private all of these are going to be private after we add Authentication so now let's copy this whole thing paste it in four times because we're going to have four different functions the second one is going to be we'll call this set goal make it singular and then let's see we'll change this stuff up here so this will set a goal and it's going to be a post request since we're setting it or creating it to the same route and then let's see for the response here we'll just copy this and paste that in all right and then let's see down here this one is going to update goal and it's going to be API goals slash and then ID and it's going to be a put request since we're updating and we'll change the name of the function here to update goal oops and then let's grab this okay we'll paste that in here and then to delete we'll say delete goal and API goals slash colon ID and that'll be a delete request and we'll change the name of the function here to delete goal and then we'll just grab this this here oops I'll just copy that and paste that in and then we just need to export all these so we want set goal update goal and delete goal all right now we can bring those in so up here we say set goal update goal and delete goal and we just want to replace these functions so this is the post request so that's going to set goal this one here is the put that's going to update goal and then we have our delete so delete whoops delete goal so we you can see we really cleaned up the the routes file here now we can clean it up a little more and because we have these two are the same route and then these two are the same route we can do router and instead of dot get and Dot post we can actually do router dot route and then pass in the route we're looking for and then we can add on to that or chain onto that dot get and we want that to call get goals and then we can chain onto that dot post and we can do set goal and then we don't need these two lines right here so it saves us a line of code and then we can do the same thing let's copy this down and we'll say for the route of ID we want the put let's do delete is going to call delete goal and then put is going to call update goal and then we can get rid of these two lines so now you can see we've really cleaned this up and now we don't have to touch this anymore so let's test out all the routes we have our get request that's still working uh let's do Post that's working let's do put and it's going to be goals slash something that's working and delete that's working okay so now we have our controller functions here that we can use before we get into uh you know connecting to the database and or creating it then connecting to it and all that I want to set up our error Handler so first of all if we um if we want to make a post request right to API goals we need to send some data to create a goal so we would do that by adding data in the body so right here you'll see we can do raw which is just raw Json or form URL encoded and that's what I'm going to do I'm going to send a value of text and for the actual value I'll just say my first goal and obviously if I send this nothing different is going to happen because we haven't handled this yet now to get body data let's go to the pertaining function which is set goal and I'm going to do a console log of request so the request object has a body property on it and if I send this with the text in the body you'll see that it actually console logs undefined and the reason for that is in order to use body data you just have to add a couple lines of middleware so in our server.js I'm going to go right here and to add middleware we just use app.use and then on Express we have the body parser for raw Json which would just be dot Json and then for URL encoded we can do app.use Express dot and then URL encoded and we just pass in an object with an extended extended value of false so now since I added that middleware if I come back and I send this with the text in the body now you'll see that it's actually logging an object with text and then my first goal so what I want to do here is check for that so we'll say if request.body dot text because that's what I sent and obviously you know you can send other other fields here as well and we'll we'll be doing that when we get into users but uh if this we actually want to check if not so if that's not there then I'm going to set the status to something different we don't want 200 because that means everything's okay this is going to be a client error or a bad request which is a 400 status all right and then we could do this like we could just add on dot Json and we could add in a message and say please add a text field okay so now if I come over here if I send it with the text nothing hap you know same thing but if I uncheck it and don't send it I get a 400 bad request and please add a text field now I would prefer to use the express error Handler because it does have a built-in error Handler so I'm going to get rid of the dot Json still set the status but then here I'm going to say Throw new error and I'm going to say please add a a text field okay now let's see what happens if we do that we leave the text unchecked send it and we do get the 400 response but you'll see that by default the error Handler gives us an HTML page it does have what I you know the error the text I passed in but if we look at the hair and the errors the headers the content type is text HTML so what I want to do is change the default Express error Handler so to do that we need to add a middleware function so in back end I'm going to create a folder called middleware and inside there let's create a file called error middleware and all middleware is oops that has to have a an extension dot Js so all middleware is they're just functions that execute during the the request response cycle so when you make a request um so as far as what I want to add here is a function called error Handler and to overwrite the default Express error Handler you just want to pass in err here this object and then the request response and then next to call on the further middleware all right and then I want to get the status code so if it's set like I set right here before I throw the error I want that if not I want it to be 500 which is a server error so I'm going to create a variable here called status code and I'm going to set it to a ternary which is a conditional so we'll say if res dot status code meaning you know what I set in the controller if that's there then I want to use that or put that in the the value of this variable else then I want it to be a 500. then we just call res dot status and pass in that status code whether it's what I set or 500 and then respond with Json so dot Json will pass in a message and then on that error object we have a message text so I'm going to use that and then we can also get the stack Trace which gives us some some additional information but I only want that if we're in development mode so we can say process dot EnV Dot and then node underscore EnV and we'll say if that is equal to production so for in production then we only want we want that to be no else then we'll show on the error object we'll show the stack which will give us like line numbers and stuff like that all right so then we just need to module Dot boards I'm going to export an object with error Handler because you can have other types of error handlers as well if you want and then we're going to go into server.js we can close that file up go into server.js and bring in the error Handler and we're going to say error Handler and we want to bring that in from our file which is going to be in the middleware folder and then error middleware then we just want to go underneath our routes and say app.use our error Handler okay and that will that'll overwrite the default Express error Handler so now if we come back over here so before I didn't I didn't have the text field and I got a 400 response and I got this HTML so now if I send without the text field I get 400 and I get an adjacent object with the message and then also the stack which gives us some more information okay and we only need this in development mode now if I were to change my DOT EnV to you know you guys don't have to do this but if I change it to production and you do have to restart the server when you change that so now if I send that I don't get that that information I just get null for the stack which is what I want so let's change that back to development and let's restart that okay good so there's one more thing that I want to do before we get into the database and that is in the controller when we use Mongoose in each of these functions to interact with the database we get back a promise so we're going to be using a sync await so we do want to add a sink to to these functions so here sync and on the delete a sync now if by default well if you use the the dot then dot catch syntax you'll have to do your dot catch if we use a sync await like we are we would do our try catch now if I we don't want to use try catches and just use the error Handler we can use a package called Express async Handler so we're actually going to install that I'm going to open up a new tab in my terminal and say npm install and it's called Express Dash async Dash Handler and then once that installs we'll go ahead and add that up here in the controller so we'll say const and we're going to call this async Handler and set that to require s a sync Handler and then all we have to do is wrap each one of these so right before where we put a sink I'm going to put async Handler and just wrap the entire function so that will end here and then I'll just I'll just copy this we're going to do that to all these so for the set goal we'll paste that and then we'll end it paste that here and that here and then for delete same thing good so now we can save that and now we're ready to start to work with the database so obviously we have to create a database actually let me make a get commit here and you guys can if you want we'll say get add all and then get commits and we'll just say um goal goals controller and routes set up all right so let's go back to mongodb and we're like I said we're using mongodb Atlas which is a cloud database we're going to set that up there's also another tool called Compass which is uh basically a desktop app a desktop GUI so that you can manage your database from there if you want so I would suggest downloading and installing but you don't have to I'm just going to open up mine let me see I'm actually logged in here let me quit that and just open that up again so when you open you're going to have this input for a connection string so let's create our database and then I'll show you how we can connect with that so if we go to mongodb sign in excuse me you can use your your Google account or your email I'm going to use let's see I have a bunch of accounts this one I just cleared out so it's basically like a new account so we'll log in and you should see something like this we need to create an organization we want mongodb Atlas click next oh we have to name it so I'm going to use travesty media and next and you don't have to actually add anything here just click create okay once we do that we need to create a project so for the project name I'm just going to say I don't know mern app create project and once we do that we can create a database cluster so right here you'll see this build the database button now there's there's paid Services here if you're going to create a you know a real production app but there's a shared plan that is absolutely free no credit card or anything it's great for testing it's great for really small projects so we're going to choose that AWS is our provider and then everything else you can leave is default I'm just going to change my cluster name to Traverse cluster all right and then we'll click create cluster so here how would you like to authenticate your connection username password so you do have to add a username I'm going to say Brad t1234 and I'm going to use the same for the password and make sure that you actually I don't know if I entered that right um front t one two three four all right so make sure you click create user sometimes people miss that and then down here where it says uh where would you like to connect from we're going to go ahead and keep local environment and then if you click this button add my current IP address it'll add your IP address or in my case my VPN address and then we'll click finish and close and go to database okay so now this is going to take a couple minutes to create actually I already had a cluster so mine I think is all set but it might say wait one to three minutes or something like that but once you get these options right here you'll see if you click connect you have a couple options connect with the mongodb shell connect your application which we'll be using very soon and then also connect to Compass which I'm also going to show you but before that let's go to browse collections and from here you would see all of your collections if you're not familiar with nosql or a document database which is what mongodb is we have something called collections which you can almost think of as tables in a relational database in a relational database you have tables of rows and columns in a nosql document database you have collections of documents and documents are really just Json objects so the structure of them you guys should already understand so we're going to go ahead and click add my own data and I'm just going to put mirn app for my database name of course you can put whatever you want and ultimately we're going to have a goals collection and a user's collection because we're going to add authentication in the next video for now let's add a goals collection so we're going to click create all right so now we have our over here you can see we have our murnapp database and our goals collection now if we go back to overview and we click on connect let's click on Connect using Compass and then copy this connection string and I'm going to open up compass and paste that in now there's two things we want to change here one is that this test right here since I I use the name mirn app for my database I'm going to put that instead of test and then I'm also going to replace the brackets and password with my actual password which is the same as my username and then we'll click connect and now you should see this admin in local but you should also see this mirn app and if we click on that you'll see your goals collection which if we had any documents we would be able to see them here all right and you'd be able to edit them and delete them and all that so I'll just leave that open and minimize it now we want to go to connect here where is it right here connect to your application and copy that that string and then let's go into vs code and we don't want to just put this in any old file we're going to put this as an environment variable so here let's say underscore URI and then we're going to set that to that and we just want to change with this it actually puts my first database I'm going to change it to myrn app because that's what I called it and then the password of course we want to change that to the correct thing and save that and then just restart your server because you did add a new environment variable so now to connect we're going to go into our backend folder close these up here so in backend I'm going to have a folder called config and again if any of you have taken my node courses on udemy WE this is I pretty much do the same thing so in config we're going to have a file here called db.js and this file is is what we're going to use to connect to mongodb and we're going to use Mongoose so let's bring in mongoose so equals require Mongoose and just make sure you have it installed if you look in your package.json you should have it and I did also install this colors which I want to use so I'm going to actually bring that into server.js because then we can use it from anywhere so we'll just go right here and say const colors colors and set that to require colors all right and then in our dbjs we bring in Mongoose we're going to create a function called connectdb is going to be an arrow function and it's going to be a synchronous because all of our Mongoose methods are asynchronous they return a promise so here we're actually going to use a try catch and in the try we're going to connect so we'll create a variable called Conn and then we're going to await on Mongoose and then there's a function called connect so Mongoose connect and this takes in our URI which we can get from process I don't know I can't type today process dot EnV Dot and then underscore URI or whatever you called it and then once it connects I do want to just do a console log and I'm going to use backticks in here and say DB connected oops connected and then we'll do a colon space and then I'm going to put our money sign curly braces because I want to take from that connection variable There's an actual object called connection and then there's a host so I want to I want to put that there um and then I do want this to be a different color and underline so after the back tick we can say dot and there's all different types of colors we can use I usually use cyan and then I like to add an underline as well so this is from the colors package now if there's an error we're going to first just console log that error and uh we're going to close the process so we'll say process dot exit so we want to exit the process with failure so we pass in a 1 here and then all we have to do is export this so module.exports connect DB and then we just need to bring it into server.js and run it so in server.js let's go right here and say cons connect DB and we're going to get that from Let's see we want to go dot slash config slash DB and then we just want to call it so we'll go right here we'll say connect DB and run that function so now you should see in your console oops what am I doing you should see something like this so it's just showing my host and it's in cyan it's underlined and of course you can use different colors if you don't get this you may it might take like 10 to 20 seconds and then you'll see an error if that happens it's usually because you forgot something in like uh the dot EnV so maybe you forgot your to put the password or you put the wrong password or maybe you put um the wrong uh you didn't set up the database access right so if we go into here and you go to network access make sure that your IP address is in there or you can also click enable for everyone so just make sure that that stuff is all set if you do see any errors you know so let's close that up and now that we're connected we can start to create our models or I should say our model we're going to do the users model in the next video right now we're going to create our goals model so in the back end create a new folder called model and this is where we basically Define any resources we have you know blog posts to Do's or whatever it is that you have in your application we're going to create a goals or goal model dot JS file so here's where we Define our schema which is going to be the fields for this particular resource now for our goals we're just really going to have a text field that's really it aside from some time stamps and also the ID obviously and the user now the user We're not gonna we're not going to create that relationship until the next video because we do you know we need to have our users model first so this is actually going to be pretty simple first we're going to bring in Mongoose so let's require mongoose all right and then we're going to create our schema so let's say const goal schema and we set that with Mongoose Dot schema and then we pass an object in with our Fields so like I said we're going to have a text field and you just need to define the type now you could do this or you can set text you can set it to an object and then have a type of string and then you can also add like unique which we don't need this to be unique of course required so we'll say required which you can set to True like that or you can set it to an array with true and then a message like please add uh please add a text value all right and that's pretty much all we need now for time stamps we could add them manually or you can go after this curly brace and add a second argument here after your schema of an object and then we can say time stamps and we just set that to true and that'll create a an updated ad and created that field automatically all right and that's all we really need here so we just want to export it so module exports and we want to export Mongoose dot model and we're going to name this the goal model and it's going to take in the goal schema which we just created so pretty simple now what we can do is go to our controller we can close up that let's go to our controller and we can bring in our model so go set that to require and then we want to go let's see we're in controller so we want to go out of that into model actually that should be models not model let's rename that all right so it'll be models and then slash goal model and then this will have a bunch of mongoose methods on it that we can use to create in our database or read or whatever it is that um you know that we want to do so let's start off with our get goals remember this is connected to this route so basically all we need to do here is create a variable called goals and we can get them from our database through our Mongoose model we need to await because remember this this is asynchronous and we can take our model and it has a method called find and you could pass in an object and find it by something actually later on we're going to find it by the user but right now we're just going to get all of them and then as far as what we want to return instead of just a message we're going to return the goals and now if I come over here to postman they make a get request to API goals goal dot find is not a function let's see um goal model okay that's weird what did I mess something up in here oh I get two P's in exports all right let's try that again so we'll go ahead and send and we get a 200 response with an empty array which is what we should get because we haven't created any goals so let's do that now we're going to go to the set goal function and we check for the text if it's not there we throw an error if it is so we'll just keep going here let's say Kant goal and let's await and then goal has a create method that we can use and we want to pass in an object I'm going to set a text value which we can get from request dot body dot text okay and then for the Json that we want to send back let's get rid of this and we're just going to send back that goal so now let's try to set a goal so come over here I'm going to open up a new tab and we want the same endpoint so we can copy that and just make a post request with a text field so click on body URL encoded and let's say text and we'll say my first goal and send and there we go we get back at 200 we get back the new goal with the text the underscore ID is the field that mongodb uses and created at updated at so if we want to create another one let's go ahead and just do my a second goal and we'll send that and now if I go back to the get request and send that again now you can see we have two goals so next we want to be able to update so let's go to our update function here and first thing we want to do is get the the goal that we're trying to update so we'll say cons goal we're going to await our go model and use find by D and remember the way we get the ID is with request Dot params dot ID because that's going to be in the URL and then we'll check to make sure we have it so we'll say if not go then let's do a res dot status 400 because they are not you know providing the the goal the ID and then let's say Throw new error and we'll just say goal not found okay so that'll get the goal then we want to update it so I'm going to say const We'll create a value or variable of updated goal not update make sure it's updated because we called this update goal and then we can await Gold Dot and then there's a find by ID and update so you can see Mongoose makes this all really easy we just pass in our ID which is request.params dot ID second argument is the the data which we're going to do request.body which will be our text our updated text and then our last a third argument with options an options object with new that will set to True which will just create it if it doesn't exist and then as far as what we want to return or respond with it's going to be that updated goal so now let's come over here let's open up a third Tab and I'm going to let's see the end point is going to be goals but then we also need an ID so I'm going to get the ID of the second goal this right here let's grab that and let's put that in the URL and let's make a put request and then in the body I'm going to say I want the text to be changed to updated goal we'll send that and we should get back the updated goal and if I come back to the get request and send it again you'll see we have my first goal and then we have the updated goal and then the last thing is the delete so what I want you guys to do is pause the video and see if you can do this yourself I'll give you one hint and that is that once you get the goal once you you know find it you can use the dot remove method to actually remove that so if you want to try it out go ahead so we're going to get the goal which I can actually copy from here and then we'll paste that in here so we're going to get that goal and then like I said there's a remove so we just need to await goal dot remove we don't even have we don't have to assign it to a variable because there's no reason to save it uh it's not going to be there I'm sorry remove has to be a function but what I'm going to return is just an ID so let's say ID and I'm just going to return that with request.params.id and the reason I'm doing this is for the front end later on we're going to need the ID but that should do it so let's come over and instead of a put request let's delete this second goal so I'm going to go ahead and send that we get back the ID but if we go back to our get request and we send you see we only have one goal so that was deleted so we now have complete crud functionality for our API now later on in the next video we're going to create authentication so we'll create a user's model we'll have a login a register so we still have a lot of work to do and even after that we're going to create the front end so right now I'm just going to make we'll say git add all and let's say git commit M and I'll just say initial rest uh initial rest API for goals or just rest API for goals okay and I'll have the code in the description as well all right guys so that's it I will see you in the next video I'm not sure exactly when that'll be it might be right away or it might be a couple days but that's it thanks for watching and I'll see you soon
Info
Channel: Traversy Media
Views: 312,838
Rating: undefined out of 5
Keywords: MERN, MERN Stack, react, express, mongodb, mongoose, learn the MERN stack, javascript, node.js, REST, REST API, RESTful API, Express API, CRUD API, API
Id: -0exw-9YJBo
Channel Id: undefined
Length: 57min 34sec (3454 seconds)
Published: Mon Feb 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.