MERN Stack Tutorial #6 - Controllers (part 1)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so then we're up and running now with our database and we've seen how we can use our workout model to add new workout documents now i want to fill out the rest of these handler functions to do things like get workouts update them and delete them from the database collection so i could write all of that code in this file as i have done here for the post request handler but i don't want to do that because this file is to register the different routes and i don't want to bloat it with database logic and other stuff we might need to do in the handle functions so instead what we'll do is create a controller file which is going to contain a bunch of controller functions one for each of these different routes and then we can call those functions directly from this file so i'm going to create a new folder over here in the backend folder called controllers and then inside there a new file called workout controller.js and inside this file we're basically going to create a bunch of functions that we can reference then inside this router file right here or here or here instead of hard coding those functions in this file and it keeps this file a bit clean with him so we need functions to get all workouts to get a single one to post a new one delete one and update one as well and we're also going to need to import the workout model inside this file as well because we'll be using that to interact with the database so i'm going to cut it from here and i'm going to paste it over here like so now then let's do a few comments for the different functions that we need so we need a function to get all workouts so let's do a comment for that and then we also need a function to get a single workout and then after that let's just spell this correctly a not s after that we need a function to create a new workout so create new workout we also need one to delete a workout so we'll say delete a workout and then finally want to update a workout date a workout like so awesome so now we can flesh out these functions now we're going to start with creating a new workout because we already kind of have that function right here yeah so let me create the function first of all so const create workout and you can call it what you want it doesn't really matter just make sure it's pretty descriptive and this is going to be an asynchronous function and also it's going to take in the request and the response object because basically they're just replacing these functions right here and they taking the request and the response object right so what i'm going to do right now is basically just copy this or rather cut this and i'm going to paste it inside this function because it's going to do the same thing all we're doing is grabbing these properties from the request body and then we're trying to create a new workout returning that workout jason catching an error if there is one and returning an error message so let me just do a comment right here to say add dark to db that's what we're doing right here so that's that function and if we go back over here now we can delete this function right here and basically we just want to reference the create workout function instead now in order for this to work we need to export that function inside this file and we can do that at the bottom of the file remember we can export things by saying module dot exports and we're going to set it equal to an object and inside the object we're going to have different properties which are the functions so one of those is create workout right so we're exporting this now inside this object and we can import it inside the other file so now i could go over here and underneath this i could say const and we want to grab a few things so we'll do that inside curly braces because we're destructuring we set that equal to require and then the path to the workout controller so that's dot dot forward slash to come out of the routes folder then into controllers and then we want the workout controller and the only thing we want for now is the create workout function now i've put this on a new line because later we're going to be importing other things on each line because we're gonna have about five or six functions in total so we have the create workout now and we're just referencing it right here so now when a post request comes in we fire this function which is this thing over here it's asynchronous and it takes in that request and response and it does exactly the same thing it just tries to create a new document so that's going to do exactly the same as before but now we're organizing this in a better way okay cool so let's also do the top function get all workouts so we're going to say const get workouts and we're going to set that equal to a function in fact it's an async function all of these are going to be asynchronous we're taking the request and the response object and then inside here we can say const workouts and we set that equal to a weight and again we use the workout model and the way we get all of them is by just using the method find and then as an argument we have to pass through an empty pair of curly braces now if we were just finding one or a subset of documents we'd pass through a property name here for example i could say reps 20 and what that would do is find all the workouts in the collection where the reps property is 20. we don't want to do that we want to get all of the documents so we just leave this object blank and also we want to sort these documents so we can tack on a sort method and we want to sort by the created at dates so i can say sort by created at like so and colon and this is going to be -1 so then that's in descending order so when we list them on the web page later it's going to be the newest ones at the top okay and then all we have to do after this is send a response so response.status and that's going to be 200 meaning all okay and then send back a json response where we send the workouts so this gives us all of the workout documents right here in an array and we're sending that as json back to the browse other clients okay cool so now we have those two functions done there is one more function i wanna do in this lesson and that's just to get a single workout now i'm gonna flesh this out but it's not gonna work the first time we try it out so we'll come back to this in a minute as well just to make it better but for now let's just flesh it out so we'll say const get workouts and we'll set that equal to an async function again we're taking the request and the response object and inside here we want to basically just find a single workout this time so we can say const and we want to grab the id from the route parameter remember the route for this if we come to the route file is forward slash id so we want to grab this changeable part of the route whatever the id is of the document so we grab that using a bit of destructuring um we don't need the equals there so const id is equal to request and all the route parameters are stored on a params property so we're grabbing the id property from the route parameters that's all we need to do and it gives us then this id property whatever we type into the address bar or the request so we have the id now which we need to try and find a single document and then inside here oh that should be singular by the way get workout inside here now we can use the workout model again to try and find it so i'm going to say const workout is equal to a weight workout with a capital w and then we're going to use a method called find by id like so and then all we need to do is pass in this id property right here we get from the route and all we have to do then is say if we don't get a workout back so if that workout doesn't exist then we want to send back some kind of error so we'll return right here a response dot status and we'll say 404 because it can't be found and then jason and inside this json will have an error property and that error is going to say something like no such workout okay so if we can't find it if that document doesn't exist this will basically be null if that's null then this will fire we return a response we set the status and we send back the error no such workout now the reason we have to return here is because if we don't then it's going to carry on and fire the rest of the code so we have to return right here because we don't want it to carry on and fire the rest of the code so after this what we're going to do is get the response and we're going to send back a status of 200 because if it doesn't fire this code it means we've found a workout we have a value for it so the status is 200 and the json that we send back is going to be the workout that we find right here okay so that's all there is to it like i said this isn't going to work fully this function and we'll see why later on but for now what we want to do is we want to export this function and this function as well so let's do that up here so we'll say get workouts and also get workouts like so and now we can import those in the other file so create workout get workouts and get workouts like so and we want to register them right here so this is for all workouts so we can delete that and say get workouts and then get a single workout so this is get workout like so whew all right so we've done a few of those functions let's try them out now in postman all right then so to begin with i'm gonna send a post request again remember the behavior of this should be exactly the same as before it's just that we've organized it in a different way using a control function instead so let's add on the reps and set that to 40 and we'll change this to bench press and we'll change the load to 25 so if i present hopefully we'll get that workout back yet we do so that's worked all right cool i'm going to copy this id right here because we're going to use it shortly to grab a single document so copy that and i'm also going to save this particular request right here because we have this body and i want it to remain like that for later so i'm going to press ctrl s and cross this off all right so now we want to get all the workouts so let me send this now and we can see this has worked also and if we scroll down we can see we have two documents and that's how many we have in the database awesome so that's worked the next thing we want to do is go to this one over here and we want to paste that id inside here so this is a get request for a single document remember so it should hopefully get that document we just created so if we send this and we do awesome that's worked all right so i did say that that function to get a single document might not always work so check this out if i put in some kind of id that is completely random and short if i press send now then you can see we could not get a response and in the console over here on the server we can see it's crashed and there's an error so if we scroll up we can see that the error right here is because the id the object id so you know the id of the document that we tried to find um it says right here that it must be a string of 12 bytes or a string of 24 hex characters right so that error is being thrown by mongoose and what we need to do first of all before we try to find a particular document so right here before we try to find it we need to make sure that the id is kind of like a valid type of id it is in fact a mongoose or mongodb type of object id all right so what we're going to do is first of all import or require mongoose at the top to do this so we'll say constant mongoose is equal to require and it's mongoose that we want and then down here before we try to find anything we're going to do a little if check to check the id so i'm going to say if and then inside here i'm going to say not first of all mongoose dot types with a capital t dot object id and then we can use a method on this called is valid and we pass in the id right here so what this method does is it sees if the id that we've got is valid now if it's not valid because we've added this exclamation mark right here then we'll do something in this if check and what we want to do is return a response where we set the status to be 404 and we want to send back some json and we're going to have an error message on that json and we'll just say no such workout okay so now it's not going to throw that internal error instead it's going to do that check right here and if it's not a valid object id then we're just going to return this json error right here if it is valid it will carry on and it will try and find the workout okay so i'm going to save that make sure this is restarted it has and we can now try this out again in postman okay so i'm gonna send the same request to this same id that's not valid and if i send it this time hopefully we get a response which we do and it says error no such workout awesome so that's working and if we go to all the workouts just to grab another id let me grab this one like so and come over here and paste in just to make sure this is still working send that and we get that document back awesome so now we've created three of those controller functions in the next lesson we'll finish off the other two
Info
Channel: Net Ninja
Views: 69,067
Rating: undefined out of 5
Keywords: mern, mern tutorial, mern crash course, mern tutorials, react, mongodb, node.js, express, node.js api, express api, express tutorial, node tutorial, node and react, mern vs mevn, full stack tutorial, full stack, full-stack, fullstack, mern stack, mern stack tutorial, mern stack crash course, controller, mvc, controllers, controller functions
Id: oEHHjs1UVXQ
Channel Id: undefined
Length: 14min 31sec (871 seconds)
Published: Tue Jun 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.