Learn the MERN Stack [2] - Express API & MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right guys we're gonna get started now initially I was gonna have you clone the react Express starter we actually created this a couple months back in a video if you want to check that out but it's basically just a very simple nodejs server that has one endpoint for API customers and it's just a hard-coded array and then we have our client folder which has the react app inside of it just just a boilerplate react app and in the package Jason we have some scripts and we're using concurrently to basically run the server and the client at the same time the server runs on port 5,000 the client runs on port 3000 but I changed my mind about that because I don't like I like to start from absolute scratch so basically like a blank folder and the reason for that is because when I take courses or I watch series on YouTube or anything like that and they have you start off with cloning some repository it's really aggravating because you you don't know what what's in that repository for sure unless they really go over it which they usually don't and you just you don't you don't see the whole the whole picture the whole application and really understand what's going on so I'm not going to do that so we're gonna kind of build this along with what what we're doing and then maybe at the end you then you'll understand how this works which is pretty simple anyway but and then you can use it in future projects instead of starting from absolute scratch all right so that's what we're gonna do so let's open up vyas code and I just have a blank folder called myrn shopping list and we're gonna start with the back end so we're gonna start by building an express API using Mongoose to interact with MongoDB it's gonna be very simple okay the back end is very simple we're just gonna have a couple endpoints so let's create or let's just rather open up our terminal so I'm gonna open up my terminal here and we're gonna run NPM at knit so mine shopping list good version description we'll say it's a shopping list built with the myrn stack entry point I'm gonna say server J s when I build the full stack apps where we're using like a front-end framework along with node I usually like today image server J s because that's what it is the server goes to go through this name this is completely open source you can put your own name I'm gonna give it an MIT license and yes it's okay alright so now we have our package JSON file if we look at that it should look like this and we're gonna have to install some dependencies okay not too many but some so let's do NPM install Express of course which is our back-end framework that's what we use to create our routes and stuff like that we're also gonna need body parsers so that we can handle data that comes in when when a request is made to our server we want to be able to read the body for post request stuff like that what else do we need here we're gonna need Mongoose to interact with our library and let's see what the hell is that papa papa we also need concurrently ok and this is where currently is basically so we can run more than one NPM script at a time so that we'll be able to run the server and the client at the same time but we're not going to need that just yet but we might as well get it installed all right so let's install those dependencies all right so there we go we also want node Mon which will constantly watch our back end and just reload you know when we save it'll it'll automatically update so we don't have to keep breeze from stopping the server starting and so on so let's go ahead and do an NPM install I'm gonna do - upper case D which you'll save it as a dev dependency because it's not needed for production it's just a dev dependency and we'll install that okay all right so now what we'll do is add a couple scripts here we're not gonna be doing testing so we don't need that let's let's put a start script in here and this is just gonna run node and then the name of the file which is server dot J s so this is basically like to run it in production but we're gonna use node Mon so let's create another script here called server which is what we'll be working with first we're not going to deal with the client yet and we'll run node Mon server J s and the difference between these two is this if we run this we'll have to restart the server after every change every server-side change and then this will actually continuously watch it and we won't have to keep updating it okay so that's all we need for now so we'll save this and close it up and let's create our server dot J yes okay so in our server J s we're gonna just bring in what we need so of course we need Express which is our back-end framework and will require Express let's see we're gonna need two more things so copy that down we're gonna need Mongoose okay Mongoose is our RM to interact with our MongoDB database makes everything a lot easier you could use like the MongoDB driver if you want but I find Mongoose much more intuitive and easier to use and just better all-around we also want body parser and that's just my opinion guys say body parser okay so body parser will allow us to take requests and get data from the body for instance when we send a post request we want to be able to get the name of that post from the from the request so that's what we need to bring in next thing we want to do is just initialize Express into an a variable called app if I can type it so this will be evil equal to Express like that sure you guys have seen this stuff before body parser has a piece of middleware that I need to add okay so this is just gonna be app dot use and we want to pass in here body parser dot Jason dot Jason that whoops all right next thing the hell next thing we want to do is we need we need a MongoDB URI to be able to connect to obviously we need a database so let's let's take a pause here real quick and do that so we're gonna go to Emma lab calm and like I said you can use a local MongoDB database if you want the code is gonna be the pretty much the exact same except for the URI it'll be you know your localhost as opposed to this remote database but this is a really great service I highly recommend it if your if it's a production app you know a serious application I would suggest upgrading past the free account you know for the adds redundancy and in speed and storage and stuff like that but for development absolutely fine to use the free account so I already have an account so I'm going to just log in if you don't just sign up it's free no credit card needs it or anything I have a couple databases here dev connector is actually my you to me course Martin stack app but we're gonna say where is it create new and we're gonna use Amazon Web Services as our cloud provider you can also use Google Cloud or a jar and click that click continue I'm going to choose US East for my region depending where you are you may have different options I'm not sure database name I'm just gonna call it myrn underscore shopping doesn't really matter what we call it you might have to call it something different I don't know if it's unique or not and then you can see the summary everything is completely free submit the order and it's gonna just create our database once this blue key turns to a green check it's all set so we can click on it you'll see we have no collections obviously we a message saying a database user is required now it doesn't mean your M lab user account it means a user for this specific database so we have to create that and we do that by clicking the users tab and then add database user ok and I'm just going to call this user Brad password I'm gonna do Brad one two three did I do that right Brad one two three they recently made it so it has to be six characters I used to always just do Brad for the password in my tutorials but now I can't you could also make this read-only if you wanted to this account alright so we'll save that now we have a database user alright so now we should be all set here this is our URI this string right here so let's actually copy that because we're gonna need that and then let's go back to vs code and what I like to do is put any API keys any database URI is anything like that I like to put in a separate file inside of a config folder so we're gonna create a folder called config and a file called Keys dot Jas okay it's just like this just how I like to do it and then we just want to export so module dot exports an object and we're going to use URI URI as the key and then the value will be that string now it's very important that you replace this with your user so mine is Brad and replace this with your password which mine is Brad one two three so we'll go ahead and save that and now what we'll do is in our server j/s we want to bring this file in ok so let's say we want to assign it to a variable so I'm gonna say DB config let's say consti B equals require we want to require that Keys file which is in the config folder and then keys and all we want from it is the you are URI so we can say dot URI and that'll give us that value ok so now we need to do is connect to MongoDB so say connect to and we do that using Mongoose so I'm going to say Mongoose don't connect and you want to pass in that DB object okay and then this is promise base so we're gonna say dot then so once it connects what do we want to do I just want to send the console message so we can put a call back in here on which I'm using an arrow function and we can just say console.log and we'll say DB connected okay just so it just so we know that we're actually connected and then if there's some kind of error if the promise rejects then we'll get an error inside the dot catch and we'll just log that so we know what what's going on so console log error okay C will also put connect on the next line as well just to kind of clean it up there there we go all right so now that we're connected we connect to we need to actually be able to run our server so what I'm gonna do is create a variable for the port we're going to use and we may deploy this to Heroku and with Heroku you want to set it to this process dot Ian VDOT port okay this is a an environmental variable but then we want to say or port 5000 okay and then we want to app dot listen so we want our app to listen on that port so that put the variable in and can also take a call back if you want something to happen which I just want to log I'm gonna console log and just say I'm gonna put back ticks in here and say server started on port and then use the variable syntax like that and put in port okay so it should say whatever server started on port 5000 okay so let's go ahead and save this and we should be able to run it now remember back in our package jason we could run NPM start but I want to use node lon to continuously watch the server so we're going to do NPM runs server so let's do that let's go down here and let's say npm run server and there we go server started on port 5,000 MongoDB is also connected good that is what we want so what's next what's next is our API we want to be able to to get requests from our front-end from our react application to fetch items from the database to post items to the database and to delete them those are the three things that we need to be able to happen now when you're using Mongoose you want to create what's called a model which is just that it's a model of of your data it's the fields that you want and so on and an item is going to be very simple basically it's just going to have a name we'll also give it a date but the date well set to to just automatically put in whatever the current date is so let's create a folder called models and let's call this file inside here we're gonna call it item dot j/s and for models I like to always have a capital at the beginning so capital I items a s and then we're just gonna bring in Mongoose so we're gonna require a mongoose and then we also want to we're gonna be creating a schema so let's create a variable called schema like that and set that equal to Mongoose dot schema okay then what we want to do is create our schema so we're gonna have a variable called item schema and we're gonna set that to a new schema object and then that schema object takes in an object an object literal which is going to have the fields that we want now we want to name and we want to give it a type of string okay we can also mark it required so we'll say require hired Eagles true and then the only other thing that I want to put here is a date so for date will give it a type of date and then we can actually give these default values so we're gonna say the default should be and we'll use date dot now which will actually just give us whatever the current date and time is okay and that's it that's our schema and one of the reasons I wanted to do such a simple application is because I didn't want to put in a million different fields stuff like that I want you guys to see how this works without having to just you know type and type more stuff that is kind of redundant I just want you to know how it works and you can create other bigger applications if you want so let's say module dot exports okay because right now we have no access to anything in this file so I'm going to say equals item we're gonna call it item and then we just want to do another equals to Mongoose dot model okay so we're creating a model and that is gonna take in a name which will be item and it'll also take in the schema okay the model needs to know what the schema is and that's it so let's save this and now this whole model should be exported so that we can bring it into other files all right so that's that now we could put all of our routes in the at in the server j/s file you know we could do apt-get API items app dot post API items app dot delete API items ID or whatever but I don't want to do that I want to keep this clean so we're gonna have a separate folder called routes and then inside routes I'm gonna have a folder called API okay because the API is routes are gonna return jason okay if you want if you wanted for some reason to render stuff on the server maybe you have a template engine you want to render a page or whatever then that wouldn't be inside the API folder you would just you know that would be something else so I like to specify that this is going to these are API route and then what we'll do is inside here the API you fold er we'll create a file called items dot J s okay and this is where all of our routes will go now to for this items file to actually work for our system to know to look there we have to add a couple lines so one up here we're gonna say Const items will create a variable called items and we're going to require that to that that file so it'll be routes as it routes yeah dot slash route slash API slash items okay now I want any request that goes to API slash items slash anything I want that to go to that file so what we do is down here let's go right above where we define the port and let's say use routes so we can just say app dot use and we want to say anything that goes to API slash items should refer to the items variable which is this which is the file this file here alright so hopefully that makes sense and we'll go ahead and save that now we have an error here that says router dot use requires a middle err function that's because we haven't actually added anything in the items file and we need to so let's do that now so we're gonna go into items J s and we want to use what's called of the Express router so we want to bring an Express okay and then we want to bring we want to create a router variable and set it to Express dot router okay router is is part of the express object now what we want to do is bring in our item model because we need that to make basically to make queries to find we can do item dot find or save stuff like that so let's create a variable called item actually will do capitalise since it's a model and then set it to require and we want it to go to that models items item model so it's dot dot slash to go outside of the API folder dot dot slash to go outside of the routes folder and then into models and then into item okay and before I forget we need to export default router or else no other file will read what's in here I always forget to do that ah I did this I did this in the es6 fashion and we're not using babel or anything so we actually have to do module dot exports I'm glad I caught that equals router okay and you can use ESM modules and node but they're not I wouldn't suggest using it you need a flag and so on it's not like completely baked in yet which I can't wait until it is so now what we want to do is create some routes now I like to label my routes with like a declaration of comments so I like to say for instance the the actual route and it's going to be a get request to API slash items okay I also like to put the description of what this route does and if you take my udemy course we do this for every route we create and it's a lot more in-depth so this will get all items and then we'll also put in access now everything is going to be public in this particular project because we don't have any ani authorization or autumn sorry Fenne ocation which is something i may add in the future but for now everything is just public okay so let's create our route now instead of app dot yet which is why does it keep doing that instead of app dot yet which is what we would do in the server JS file since we're using the router we want to do router get okay and then we just want to put a slash here because remember everything that if if we hit this endpoint right here API items in an HTTP client it's going to go right to this file so we don't actually put API slash items in here because we're already in that route so we just want to slash okay so this slash will it represents this actual endpoint since we're using the router if we were in the server J's file then yes we would have to do apt-get API slash items hopefully that makes sense so let's put in our arrow function here with a request and response and what do we want to do here so we want to basically fetch all of the items from the database now of course there are there are none but at least we can get we'll be able to get like an empty array so we want to take the model which is item because that's what we called it right here we'll take the model and we want to use the find method so with Mongoose we have a fine method we could just do that and then this returns a promise okay so we want to do dot then and then in here it'll give us the items okay it'll fetch from the database give us the items and then what do we want to do with those items well this is a JSON API so we just want to say res dot jason and then pass in items okay but one thing I want to do is I actually want to sort these and with Mongoose we can use dot sort and I want to sort by the date okay so I'm going to say sort by the date and then we can put either a 1 or a negative 1 and I want it to be descending so I'm gonna do a negative one okay and that's it that will give us our items so let's go ahead and save that and see if we get any errors down here okay looks like everything is good now to test api's I actually should have went through this earlier but you need to use an HTTP client so I would highly highly recommend using postman which is just a phenomenal program it used to be a Chrome extension but now it's a standalone program it's it's actually built on electron which is a framework to build desktop apps with JavaScript which is incredible but you want to go ahead and download this I should have it installed I think I do one second yeah okay so I'm just going to open mine up alright and you should get something like this so what I'll do here I'll just leave it fullscreen I guess but we want to make a get request to our to that endpoint that API items and see what happens so let in here let's do HTTP make sure your servers running of course and then we want localhost port 5000 slash API slash items okay so this is good what's happening is we're getting a 200 response okay an HTTP 200 means okay that's what you want that's successful and it's just giving us an empty array because obviously there's nothing in the database so that's a good sign it's a good sign that that route is actually working so what I want to do now is create our post endpoint so what I'll do is copy this whole thing right here including the declaration and we'll change this because now it's a post requests to API items and it's going to add or let's say create creates a post and it's going to be public normally this would probably be private if you had authentication but for now it's going to be public and we're gonna make sure that this is router dot post because now we're making a post request and then as far as you know we don't need sort obviously we can get rid of that and actually we want to get rid of this item dot find altogether because that's not what we're doing we want to construct an object to insert into the database so I'm gonna create a variable called new item and set it to new item because item is the name of our Montt our model okay we brought it in right here if this was our like a post item or I'm sorry a post model or a product or something it would be post or product whatever but we're gonna say new item and then pass in an object and all we need is the name now the name is gonna come from the request it's going to come in the body of the request and we get that with request body dot name and using the body posture allows us to do this now we don't need anything else even though if we look at the model it has a date the date is gonna be automatically inserted and it's going to be that whatever the current date is so we don't actually need to put this in if we had other fields here we would need to handle those but we don't so we just need the name so once we have that variable new item set to a new item object we can actually take that new item variable and we can call dot save okay because it's not saved yet it's just basically created in memory now we want to save it to the database now this is promise based as well so we can say dot then and then what do we want to happen it gives us back the item that it's saving and what we want to do is just res dot Jason and we want to spit out that item in Jason okay and that's it so let's save that and now we'll do is we'll test this out just like we did with the get we want to go to postman why isn't this opening all right so now what we need to do is make a post request to the same URL URL it's api items except we want to add a header value of content type because this has to be jason so the content type value should be application slash jason and then what i'm gonna do is go down here to raw i'm sorry i want to go to body weight headers yeah i want to go to body and then raw sorry about that and you can see it should say jason application right here and then we can just put in custom jason now with with with actual jason not an object literal but actual jason the keys and the values should be in double quotes so we want to say name and let's say milk for the value okay so what I hope to happen is we send this request with milk in the body and then it gets added to the database and it sends back a 200 response along with that new object that new item so let's go ahead and try it we'll click send and there we go so we get a 200 response let's make this pretty and you can see it gives it back we have the name of milk it has the date it also has an ID because with MongoDB when you insert something by default it gives you back an underscore ID value okay so this is this is what it gives us for an ID and that should be now in the database so if I go to Chrome if I go to Chrome and we go to M lab and I reload my M lab interface look at that we now have an items collection we didn't have to go and create this items collection like you do in in SQL a lot of times you have to go in and create your actual tables it just gets created and if we look in items we have milk okay so it actually got saved to the database if we want to try again to add something else we can just keep this open we can change this to eggs and click send and we get back that object and it should now be in our database if I reload there it is eggs all right so the last thing we need to do in our back end here is the delete we want to be able to delete these these items as well so what I'm gonna do is copy this whole thing and let's say this is gonna be a delete request now the delete it's gonna need an ID so it's gonna be the route is gonna be API items and then whatever the ID and let's say this will delete a post I like I put post item did I do that up here too I did this should we create an item create an item alright sorry about that so we want to delete an item so this will be a router dot delete okay it's gonna be a delete request and we want to pass in : ID which is like a placeholder for whatever we pass in as an ID now we have to first find it so what I'm gonna do is I'm going to delete all of this and we're gonna say item and we're not going to use find we're gonna use find by ID see all these methods these are all available with Mongoose but we want to find by ID and then just pass in the ID now the way that we get it from the parameter because it's going to be in the URL the way that we can get it is by using request dot params dot ID that'll actually fetch it from the URI and then that'll give us a promise back so we do dot then and that will give us the actual item that's it'll just give us the item we're searching for no delete yet and then we're gonna set an arrow function and we want to then remove it so we're gonna say item dot remove and then that will give us a promise so we can say dot then and then all I'm gonna do is put in a callback here and we're going to res Jason and it's up to you what you want a return I'm just going to return an object that says success true okay and your responses are completely up to you now with this item fine by ID if we pass in an ID that doesn't exist we should it should call it should get a promise reject so we should be able to do a catch right here so that's what I'm gonna do is I'm gonna do catch and then here we'll pass in error and then we want to send back a response but we don't want to send just res dot Jason we don't want it to be a 200 response which means everything's okay we want a 404 which is a not found error so we're gonna do res dot status pass in 404 and then do dot Jason and what we want to send and all I'm gonna send is we'll say success false I guess you could be more specific but that's that's fine for now I guess so let's save that and see looks like we have an error catches not a function wait a minute that's because I put it on the actual router this should be oops this should not be here this should be right here like that okay all right so let's give it a shot we'll go let's see we'll go to post man and we want an ID so this egg's right here has this ID so I'm gonna just copy that real quick and then let's make a delete request to API items slash and then that ID and send and we get success true now what we'll do is make a get request to API items so we can fetch all the items and eggs should be gone so let's do that and there we go we just have milk okay now if we were to try - I'm just gonna open up another tab here if we were to try to delete one that wasn't there so if I go delete pass that in and let's do just an ID that doesn't exist and send we get success Falls okay and if we do this get requests again this get requests will get the same thing just milk alright so that's it guys I'm not gonna save this our back end is now complete for this application alright so in the next video we're going to start to create our react application so we're gonna start to work on the front-end to deal with this back-end and this is a very simple back-end guys if you take my udemy course you'll see that it can get a lot more difficult and it can even get a lot more difficult than that especially if we're dealing with like authentication which again I may get into in the future but for now I just want you to understand how everything works together and you've now built the backend API alright so I will see you in the next video
Info
Channel: Traversy Media
Views: 230,738
Rating: 4.9603844 out of 5
Keywords: mern, mongodb, express, express js, expressjs, express api, node
Id: 5yTazHkDR4o
Channel Id: undefined
Length: 35min 39sec (2139 seconds)
Published: Wed Jun 27 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.