MERN Stack Tutorial #5 - Models & Schemas

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so then now we've connected to the database and we need to start interacting with it to add documents then retrieve them and also update them as well and we'll be doing that all from inside our route handler functions but the first step is to create a schema and a model for our data so that we can be sure that every document that we have and we save to a database collection follows the same predictable structure the kind of data we'll be using is workout data or exercise data so we want to make a schema and a model for that so to do that we'll create a models folder first of all and then inside that i'm going to make a workout.js file and then in this file we can define how our workout documents should look so the first thing we need to do inside here is again require mongoose so let's say const mongoose is equal to a require and we want the mongoose package because it's mongoose that allows us to create these models and schemas for our data in the database mongodb alone is schema-less all right so now we need to create a new schema but first we'll say const schema capital s is equal to mongoose dot schema right and we're going to use this now which is a function to create a new schema so let's say const workout schema since we're creating workout documents is equal to a new schema like so and invoke it and this creates a new schema for us now we're passing as an argument an object where we define this schema so what does our data look like what should a typical workout object or document look like well it should have a title property so we add a title property to the schema and then this can be an object where we define bits of information about how the title property should look so for example we can add a type property in here to say that it should be a string so if we try to save a new workout document to the database where the title isn't a string it's a number then it's not going to allow us to do that it enforces this schema we can also say that we want this to be required by using a required property and setting equal to true all right now we can go deeper into this but for now this will be fine so that's the title property and then we're going to have a reps property to say the number of repetitions that we did this exercise and the type of this is going to be a number and required is also going to be true okay so again if we added in i don't know a reps property which was a string like abc or something then it's not going to allow us to save that to the database because this must be a number all right so next up we want the load and that's going to be a number as well so we'll say type number and then down here we'll set required to be true as well okay and that's all the properties that i want for now on each workout document alright so we have a title reps and load and all of these things are required so if we try to save a new workout document where one of these fields is missing then again it's not going to allow us to do that it enforces this schema for us which is nice now as a second argument to this new schema thing right here the first argument describes how the object looks as a second argument i'm going to pass through another object which is going to have a timestamps property and i'm going to set this equal to true and what that does is when we try to create a new document it automatically adds a created app property for us to say when the document was created which is nice and also i think it adds an updated property as well so when it was last updated so that's our schema pretty simple right and now what we need to do is make a model based on the schema so the schema defines the structure of a particular document or a type of document inside our database what a model does is apply that schema to a particular model and then we use the model to interact with a collection of that name so let me write this out first of all and then i'll explain it i'm going to say module.export first because we want to export the model and then we say that's equal to mongoose dot model to create a new model we give this model a name so i'm going to call it workout singular because then it's going to pluralize this to create a workout collection for us automatically which is nice and then as a second argument to this we pass in the schema workout schema right so this creates us a model now which we're going to import in other files later on and we'd import it as something like workout right and then we'd use that workout model to interact with the workouts collection because it automatically creates a collection for us based on this name it pluralizes this and builds that collection in the database for us so we'd say something like workouts and then if we wanted to get them all then we'd say dot find and that would find all of the workouts within the workouts collection for us or if we wanted to add one we use a different method so this is what we use the method on the model itself the schema defines the structure of the documents that we save to that collection hope that makes sense it's going to make more sense in the future when we start to use this model to do things like add new data or get data and in fact we'll just do a test of this straight away inside the routes file so go to workouts.js right here and what we'll do is we'll just fill out this handler right here to add in a new workout so remember this is a post request and when we send a post request we'll send out the data that we want to create a document with so we'd send the title we'd send the reps property and we'd send the load property and because we used this middleware before express.json all of that request body that comes along with the request is going to be passed onto the request object so we can use it so i'm going to grab all of those three properties from the request body so i'll say const and we'll use a bit of destructuring we'll say title load and reps with the other one we set that equal to request dot body okay so we'll send these along with the request later when we try this out from postman but now we're extracting them and what we want to do is we want to try to create a new workout document inside the workouts collection and like i said we're going to be using the workouts model to do that so we need to import it at the top up here first of all so let me come under express and say const workout is equal to require and it's going to be dot forward slash models forward slash workout model like so because that's the name oops is it models okay this is just called workout what i'm going to do is i'm going to call this workout model so let me rename this call it workout model like so and in fact we'll change this to be just lowercase like so so now we have this workout model and we can use that to try and add a new document to the workouts collection so the way we're going to do this is by using a try and catch block because we're going to try to do something but there might be an error and if there is an error we can catch that error and do something with the error so let's do that catch error like so all right so ignore this for now we're going to replace that later on what do we want to try and do well we want to try to create a new workout so we'll say const workout is equal to workout with a capital w that's what we just imported the workout model and then we use a method on that called dot create now this is asynchronous right here so what i'm going to do is change this handle function to be an asynchronous function so i can say async like so and when we do that we can use a weight right here so basically now we're storing the response of this in this thing and normally when we create a new document once that's been created the response we get is the new document that was just created along with the id of that document so we're storing that inside this workout constant now now inside this create method right here we have to pass through an object which represents the new document that we want to create now we just want to pass through for now these three properties the title load and reps so i can say title load and reps all right and it's just gonna create a new document now for us with those three properties okay so once it's done we have that workout object and that represents the document that was just created and what we can do is send a response so i could say response we'll tack on a status code as well of 200 just to say everything was okay then we'll send back some json and the json we're going to send back is just the workout object right here or the workout document that we got back all right so that's all we need to do right here if there is an error we catch the error right here and what we'll do is return some kind of error message so i'll say response dot status right here set it to be 400 which is an error code and then we'll send back some json and the json we want to send back is an object with an error message and the message is going to be the error that we get back right here so error dot message because it has a message property on it okay and now we can get rid of this response down here because the responses are up here we either respond with this the workout if it was a success or an error if it wasn't and that's all there is to it we're using our workout model now to create a new document all right so let's give this a whirl open up the terminal make sure this is running and there's no errors that's not cool and let's head over to postman all right then so in postman we want to open up our post request right here and we want to add body to the post request this is the data we're sending along with it now right here you want to go to raw and then change this to json because we're sending raw jason right okay so remember we need those three properties sending along the title first of all which we'll just say is going to be situps that's the title of the exercise then we'll also send a load which is a number and that's going to be zero since we're just doing sit-ups and then also the number of reps and we'll set that equal to something like 50. okay so now if we send this post request then it should look at this and it should add that new document based on this and we should receive that document back as a response so let's press send and see if this works and you can see we get a status code of 200 and also this document back right here so it has these three properties on it but also an id that is provided by mongodb and also these timestamps created that and updated that all right so it's created that document for us awesome now then watch what happens if i get rid of one of these fields so if i just send a longer post request with two fields and press send then we're going to get an error response back workout validation failed and it says that reps is required so remember that model we created it said that the reps property and in fact all the properties were required so it's not allowing us to create a document unless we have that required property which is cool so we know that that kind of mongoose validation is working as well and finally my friends i just wanted to come to the mongodb website where we can see our database and i wanted to browse the collections to make sure that that document was saved so if i click on that we can see down here we have a workout collection that was created for us automatically when we try to make a new workout document and inside that we can see a single document which is awesome so it's worked and it's not saved that second one where it didn't pass the schema validation so everything's working now we have everything up and running next i want to talk about something called controllers
Info
Channel: Net Ninja
Views: 80,025
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, mongoose model, mongoose models, mongoose schema, schema, mongodb schema, schemas, mongoose schemas, mongodb schemas
Id: O8IipcpTmYU
Channel Id: undefined
Length: 12min 43sec (763 seconds)
Published: Mon Jun 20 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.