SPEED RUN: Build a CRUD API with Node.js + Express + MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello friends welcome to garden with cj this is going to be a 20 minute speed run i'm gonna i'm just gonna code as fast as i can to try and make a crud application create read update delete we also just got into a hype train people are hyping i don't know but we gotta go so let's let's just let's just jump right into it am i going to be able to do it i don't think so i'm going to try my best i'm going to try my best but here we go so uh i'm going to make a server folder and actually for the sake of time i'm going to use a a generator so mpx create express api uh we'll call it server thank you very much the shibas for the gifted sub so this is a generator that i created which will generate a base express app give us all of the things we need like express um it might it might add chords it'll add a logger it has all of our middlewares basically we're set up and ready to go so that we can focus on the the crud aspect of it um so thank you very much posivious for the bits thank you um yeah i've used yarn before but i prefer npm okay so that generates this app for us uh if you take a look at the readme it tells you all the things that we get we get morgan for logging helmet dotty and v but basically we have a base app basically but from here we need to build it out um so so many things are i i appreciate you all for the bits i'm gonna acknowledge all of the bits after after the trade is over so we have a basic express app we have all of our middleware set up we're gonna focus on just creating the crud routes um and so here in the api folder i'm gonna create a new file and i'm going to call it um faq so we're going to create read update and delete frequently asked questions so here we go two minutes in this is the actual code so we need to bring in express um and then we're going to create a router uh express.router so a router is the thing that's going to have all of our routes and then we're going to export it so a module that exports that router um and we're going to need several different routes so we're going to have uh the first we're going to do the get so we'll say router.get slash so when we crest request slash faqs that'll give us all of the frequently asked questions um so we're gonna have to fig fill that in rec resin next we'll do it okay so this is the uh read all we also need the read one so you can get one specific frequently asked question by id we'll be able to create one so that's going to be a post request to just slash so that will be create one we'll be able to update i guess that will be a put to some id we'll update that one and then we will be able to delete one as well so that's going to be a delete request delete to some given id cool um for now we're just gonna res.json a message hi hello read all hello read one uh hello create one hello update one and then hello delete one yeah done shipping okay so that should give us our routes now we need to actually mount this router so the way i have this set up is we have this api router which mounts other routers inside the api folder so i can bring in faqs and we're talking about frequently asked questions i'm actually going to rename this with a s plur i'm going to plur pluralize it faq it's great okay we got that um so we brought it in now we need to mount it and so i'm going to say router.use slash faqs with that router so all of the routes inside of that router that we just set up will be prepended with slash faqs this api router is in turn mounted at the root at slash api v1 so api v1 faqs will uh should serve that up so let's go ahead and try to run it npm run dev oh yeah we can't use port 5000 because something's already using port 5000 um so let's do this we're going to create a dot envy and we're going to set our port test fail set a report uh oh no not nine nine nine nine nine nine all right try again address and use what i guess i have so many services running on my computer uh 4242 there's nothing running on port 4242 there we go so um and let me just put that up there so you can see it if we go to por if we go here we have our basic api if we go to uh slash api v1 we should see the api route if we go v1 faqs this will say hello read all i'm going to use a tool called insomnia to test all of the other routes for like post requests and patch requests and stuff like that so let me open up insomnia test failed successfully successfully um all right just a second um new folder uh crud faqs am i going to be able to do it i don't know i don't know okay so this is a oh no the timer reset uh we were we have basically 13 minutes left how many seconds are in 13 minutes tell me hurry hurry um thank you all for the hype train very much appreciated i'm wasting time we actually like how many seconds what's 12 times 60. six times two is 120 uh 780 okay we're gonna go with 7 30 then there we go good enough okay so this is a tool called insomnia and it allows me to make requests to my my access point or to my endpoints so i can do this that should give me read all if we do a get slash sum id like id 5 that should read one great work if i do a post request to slash frequently asked questions that will attempt to create a frequently asked question if i do a put to frequently asked question five that will update the item with id5 and if i do a delete that should delete the item with id5 great okay so i'm gonna install a few other things to get the rest of this going we're going to install a tool or a library called monk it's really easy to crud mongodb using this library called monk you could use mongoose monk is good i like it and we're also going to use uh joy which is a schema validation library so we'll use that to validate incoming data to make sure it has the right format i think they renamed themselves or they're under the happy namespace at happy joy yeah i can never get monk to work well i'm going to try my best to get it to work so monk lets us talk to mongodb happy uh happy joy happy happy joy joy it's a is a schema validation library uh oh and we got some got some security vulnerabilities let's fix those ten minutes left can we do it the thing is like it's an api will we be able to create a front end i don't know i don't know we're going to try our best um so i'm going to need another variable here that's like uri and right now i can just do localhost slash faqs so that's going to connect to mongodb that's running on my computer to a database called faqs all right um this is a speedrun i feel like i'm slowing down but let's let's bring in monk so we're going to bring in monk and then we can connect to the database so the way you connect to a database is you just say monk and then you pass in the connection string so i'm going to say process dot env.mongo uri and that should connect to the database and then to get access to a specific collection so let's call this the faqs you just say db.get and then you spec specify the name of the collection so if i've done that correctly really all we need to do is is query that database so i'm going to do a try catch so we'll attempt to say all of the items are faqs.find and this is a function that returns a promise so search my database for all of the faqs and then once you get those back we're going to respond with them uh but if there was an error we're just going to forward it so if it couldn't connect to the database or something like that we're going to see that error so now if we make a request to get all faqs we should see an empty array and we do look at that we're connected to the database we have an empty array so actually that's all we need to do for get all um let's go ahead and set up create1 so we're going to need a try catch we need to validate the body so i'll say um yeah yeah yeah it's working it's great so let's create a schema we're gonna go ahead and bring in joy um [Music] we'll bring that in from at happy joy i need to go look at their docs to figure out how do i create a schema um object we'll figure it out but basically we're going to specify what goes into a frequently asked question um so let's look at their documentation and api um we'll look at examples i guess joy.object yeah and then you pass on all the properties you want great so uh what will our frequently asked questions have they will have a question which is um joy dot string dot trim dot required so a frequently asked question must have a question a frequently asked question must have an answer um and what else potentially we're not going and it's required not require required and um we probably won't have this for all of them but maybe we'll have like a video url so potentially if there is a video associated with um this frequently asked question then we'll put that in uh what else what else do i need i think that's it questions answers video url we'll probably do like created app um but we'll just automatically add those we don't really need that in our schema this is good enough it's it's super easy that's all we want okay so we have this schema this is now going to allow us to validate the incoming incoming data that we send to our server so the way you do it is schema.validate and that gives you back the validate uh the valid the valid thing oh yeah yeah it does have url you're right um or uri is actually what it's called um good enough so we expect it to be a uri um we could limit it to like http it doesn't matter i'm gonna be the only one using this anyways um okay post so first we want to validate the request body um so we'll do schema.validate the data that we're gonna pass in is rec.body so rec.body is the thing that we're actually sending to the server let me just log it out to make sure that we're getting it um and if it's uh if it's valid we're just going to respond with that valid body that's.json with that with that value if there was an error we're going to forward that to our error handler and then we need to make this an async yeah we got six minutes i think this is gonna be just the api there's no way no way i could build a front end for this um in that amount of time but okay we should be able to create new or at least send post requests to create a new one so i'll do a post the body is going to be json right now i'm just going to send an empty body and we should get back an error yeah question is required so if i say question is how you do that and then we do that we should get back answer is required great i just do and then we also want a video url and if we specify that as something that's not a valid url it should complain uh video url must be a valid uri great so um and also we could just leave it off because it's not required and then that awesome so we're not putting it in the database yet we're actually just this validator if it if it throws an error that goes into our catch but if it doesn't throw an error it gives us back the validated item um and i think that should be fine what happens if i put an extra property whoa what is not allowed yeah so by default it prevents extra properties from being added on there as well okay so i think we're good to go at this point we just need to insert it so um i'll say inserted is uh await uh faqs dot insert i think that's it that's all i gotta do res.json inserted and so now if i try to put something in the database we should get back there it is and it's got an actual id so that's awesome so now it's in my database um we could do some some validation like make sure that this question already isn't in the database but that's fine let's go ahead and do git one so now i should be able to request a specific one by id so simple try catch forward the error we're going to grab the id from the uh params so rec.params and this is basically uh the parameter in the url and then we'll say uh item equals await it does need off i know but we don't have time for that faqs dot uh find one i believe is a method we can use um and we can specify our query so where uh id underscore id so in the database it's called underscore id because it's is equal to the id that was passed in um if the item was found then we're just going to return it actually we'll do an early return or an only early throw so i'll say if there was no item then we're going to return um we're actually just going to call next so that should forward onto our um that should forward onto our not found handler um not return this i need this to be an async method yeah we're using express um all right so uh find one buy that id if we didn't find it call next which should go to our not found handler but if we did find it respond with it okay so if i do a get request to faqs slash that specific id we get it back great but if i do it to something that's not found uh argument passed in must be a single string of 12 bytes or a string of 24x characters um i mean that's that's an okay error messages i'm not opposed to that uh what if we did this but we just changed value yeah then it forwards it to not found good enough good enough okay so we've got get all we've got get one we can create one now let's update one um two minutes yeah yeah we got this so update will be similar to create we're just gonna do a full-on replacement of that item so um if you're updating we need to validate the request body um and actually i'm going to yeah we shouldn't have the id there but we're going to grab the id from um direct.params again and then instead of inserting we need to grab the existing one to make sure that it exists so basically we do a similar thing to whenever we were reading one so um validate the body find one with that id if we didn't find it error aft and if we found it we know that that id actually exists and now we need to update it so we'll say updated is going to be um faqs.update and we want to update uh where the id is equal to that given id and we're going to pass in the validated schema here cool so that should do it um if we request all faqs we have that one we have this id let's say i want to do a put to faq slash that id and we're going to change this to an exclamation mark send it the update operation document must contain atomic operators ah i totally forgot so uh we actually what we actually want to do is we want to say uh dollar sign set should be the values that were passed in and that's going to set each of the properties 30 seconds ah okay so it modified it that's fine i think instead of returning the updated we'll return the value 18 seconds that's fine um and then we just got to do this 11 seconds i got it so when we're deleting by id we grab the id from the params rec.params we'll say await faqs dot delete or is it remove i forget we're out of time but it should be easy delete where id is that given id and then we'll respond or i think we'll just send a 200 status code i mean i kind of want to respond with an object i i know that like there's a rest specification that says um whenever you delete you actually should just respond with a status code and not an actual body but i don't know all right we're out of time this should work okay so uh i'll test updating one again so this should should work when we try to update we're gonna put and then uh it updated it and if we do a get for that specific one we see the updated one that's great and then if we do a delete for that specific id facts.delete is not a question uh not a function i think it's just remove then so remove all right this is it that's it we've got it success all right and now if we do a request for that one we should get for if we're not found because it's not in the database anymore and if we do a request for all of them we should get an empty array that's it we did it we created a a crud api in about 20 minutes um maybe i'll do another challenge video where we build a crud front end in about 20 minutes that could be fun but we're done thank you everyone for watching um this is not tdd no no we implemented it with uh error error first development we did it everyone say bye youtube bye youtube wow wow okay um we got a ton of supports while that was happening so i appreciate you all uh bosivious with the 300 bits uh shines love with 100 bits a light you're away with the four month three sub turtle monkey with the hundred bits the she boss with the gifted sub mr smoothie with the hundred bits posified with the 200 bits we're knocking with 100 an mb dealer with a 300 and ron [Music] with the 10 bits i don't understand ron why do you always talk about this but i appreciate you um
Info
Channel: Coding Garden
Views: 113,642
Rating: undefined out of 5
Keywords: speed run, vscode, coding, javascript, web development, stack, mechanical keyboard, lesson, api, CRUD, twitch, beginner, rest api, live coding, mern, backend, read, mongodb, node.js, pancake, delete, mean, html, educational, games, full stack web development, full stack, live streaming, full stack javascript, create, update, learn node.js, learn javascript, css, express, pancakes
Id: EzNcBhSv1Wo
Channel Id: undefined
Length: 21min 6sec (1266 seconds)
Published: Thu Jul 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.