How to create MongoDB Schemas and Data Models | Node.js Tutorials for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome hi i'm dave this tutorial is part of a nodejs express and mongodb for beginners tutorial series i'll put a link to the full playlist in the description below in the previous tutorial we went over what mongodb is and we used the mongoose js library to connect our app to mongodb today we're going to create mongoose schemas and data models that will allow us to perform crud operations on our mongodb data collections we're going to start with the code repository from the last tutorial but if you don't have it you can download or clone the starter source code from the link i've provided in the description below let's get started today at mongoosejs.com and from there we're going to click read the docs and it instantly takes us to the schemas in the docs and that is because as you see on the page all highlighted it says everything in mongoose starts with a schema each schema maps to a mongodb collection and defines the shape of the documents within that collection so you can see why they're very important and here you see an example schema they have a blog schema and they're declaring data types for the different fields inside of the documents that will be created with the data model and they also have some options here such as date they're not just saying it's a string for the body they're also saying it's going to be a date they can have default data and there's other options available as well and if we scroll down just a little bit further you can see the permitted schema types and here we have string number date buffer boolean and a few others object id is an important one that will be created automatically for us so we will not have to specify an id as you don't see one specified in their example either so now let's go to visual studio code and get started creating our schemas for both our employees data and our users data okay i'm in visual studio code and i've got the source code from the last tutorial it's linked to below as the starter source code if you want to download or clone that right now we're going to go to the model folder and we've got employees.json and users.json because we were just using the node.js file system to write to both of these files and we're going to get rid of that eventually here as we replace everything with mongodb for now just keep those files and we'll create new files for our schemas and the first one will be called employee and i'll spell that with a capital e and then just js and that's a naming standard it won't really have an impact if you don't use the capital e however it's pretty much the consistent standard that i've seen so first let's define mongoose and require that there we go and now that we've got mongoose pulled in we also need a schema with a capital s and that's going to equal mongoose dot schema once again with a capital s now that we have that we can define our schema and let's call this employee schema and that can use camel case we'll set this equal to a new schema once again capital s on schema and now we can map out our data and if you remember our employee's data was very simple it just had a first name and a last name so that's what we'll declare here now remember we will automatically have an object id created for us so we don't need an id field here and now we can say first name is type string and then we can also say it's required and that accepts a boolean so we'll say true that is absolutely required and then we'll do the same for last name and know what we could just copy this down shift alt and the down arrow for me on windows and visual studio code and make that the last name and let's get rid of the comma there and that's basically our schema very simple we've got two string fields first name and last name now at the end of the file we need module.exports and we're going to set this equal to mongoose.model [Music] now we're creating a data model right here and we'll set this equal to employee and that is uppercase first letter and then not plural once again just like the name of the file employee and then we'll use the employee schema now by default mongoose when it creates this model will set this to lower case and plural so it will look for an employee's collection in mongodb and the employees collection will be all lowercase and once again it will be plural and we can see that if we go back to the docs and we go to the models link in the docs there we go it says this in bold right here mongoose automatically looks for the plural lower cased version of your model name so in the example they give they have the word tank they defined here for the model and they passed in the string tank with a capital t but it says for the example above the model tank is for the tanks collection in the mongodb database and that's all lower case and plural all right back to visual studio code let's save this file and let's go ahead and create a user schema as well now our user data had just a little more to it so this will be a little more interesting than just the first name and last name that we had in the employee schema i'm just going to copy these imports here because we need the exact same thing at the beginning of basically every schema we create and now i'm going to say user schema camel case this is equal to new schema capital s on schema and now we have a username in our data and this is kind of like the first name last name in the previous schema it's type string and then required is true after the username we have roles now the roles data is a little bit different so we had user which was a possible role and now let's specify some data or some details about the user role here inside of an object and now we can set this to type number and we can put a default value so if not specified any user that's created will automatically be assigned the value of 2001 and that was our basic user value that we had previously applied and then the next role was editor and that had a number and then the next role was admin and that had a number notice we're not providing default values and we're not even saying they're required not everybody's an editor not everybody's an admin so these will only be added to the data that we decide to add them to as an admin could make those decisions okay now that we've defined the roles let's put in the password field this is much like we had before type will be string and required will be true and then after that if you remember we also store a refresh token and when a user's created they don't have a refresh token but after they're authenticated they get one so this is a string but it does not have a default value and it's not required because it's not always there so now we've created our schema for our users and let's go ahead and export this we'll say module.exports set it equal to mongoose.model so we're creating a data model and this will be user singular and then mongoose will once again look for users all lowercase plural but we'll match our file name so user and then we'll use the user schema that we just created okay we've created two basic schemas for our data user and employee and then we created models to be associated with those let's go ahead and implement the user schema and model and let's attach that to one of our controllers and let's do it with the register controller first that makes sense where we'd create a new user and now you'll see how much easier mongoose makes interacting with the mongodb collection than it is to write all of this stuff that we have been doing with the file system module and interacting with json files so let's simplify this file and just switch it over to using mongodb so we're going to get rid of the user db that we had up here and let's just bring in the user model so i'll define user with a capital u and set this equal to require and now we need to go up out of the controller folder and into the model folder and then we need the user model after we do that whoa i lost something there user model there we go after we do that we can really get rid of the fs promises and path we're not going to be right into a file anymore or need that we do still need to keep the bcrypt import and now let's start making changes as we handle the new user here and it'll start out the same we need the user and password to come in from the request and if we don't have those we're going to send the same information back that's a bad request but now when we check for duplicates we're interacting with a different database so now this will change just a little and we'll still define duplicate but how we get the duplicate is completely different notice we already have handle new user as an async function so right here we're going to await and then use our user model and call find one and now we'll pass in some information here we're looking for a username that matches the user that we defined from our request and after that we need to call exec here at the end now not every mongoose method needs that on the data model but this one in particular does and that is because we could pass in a callback afterwards like error result for example but if you don't do that and you're using the async a weight pattern here then you need to put exec at the end of find one and you can check that in the documentation under find one to reference if you need that or when you use any method that you're not sure of and you're using async await you should check that but this is going to return any user that matches the user that was passed in and of course we don't want a duplicate so this is the same if there is a duplicate we need to send this 409 conflict there after that we need to handle the password in the same way but after the password is created our code is going to get much simpler let's go ahead and keep the new user even though we will define this a little bit differently but we're not going to use this or the fs promises we don't need that console log there let's go ahead and keep the status 201 though because that is what we want to send when we create the new user with mongoose we can create and store so i'll put create and store the new user all at once and so what we'll do instead of defining a new user here i'm going to define result and i'm going to set result equal to a weight then our user model dot create and now we are creating a new user and let's look inside to see what we're passing into the create to make sure we have everything we want or we don't want well we do want the username and then we don't really need the roles here because remember we have the default data in our schema so it will be added automatically so we can remove that and then we pass the password and an object id will be created automatically also so this is all we really need to send through our data model and the username and password will be sent by us and then a role will automatically be created a role value and an id for the document will also be created now result will return the record that is created so we could go ahead and log the result just to view the record in the console and i'll save that i do want to discuss a couple of other ways a record could be created that you might see somewhere i prefer to do it this way because it happens all at once just the user create and it is created we get the result back but you might also see something like const new user equals and then a new user with the model and then of course you could set new user dot i'm sorry user name there we go and set that equal to whatever data you had and use dot notation that way to set the values and at the end of all of that you would want to save so then you would say const result equals and then you would have your await new user and you would call save and that would also work however that's just a little bit longer process you might also see something like the new user being created and then passing that data in like we did inside of user create so instead of using dot notation you might see something like new user equals well here we define new user but then it's equal to a new user and you're passing in the values inside of the parentheses there and then you would still need to have the result equals await new user dot save after you did this and so this happens all at once when i use user create and if i do it this other way and create a new user then you have to have another line to actually save the new user so i prefer the user.create let's go ahead and save this and now we're ready to test our register controller route so let's open up a terminal you can do that from the terminal menu or press ctrl backtick at least i can on windows and now i'm going to type npm run dev and that should start up nodemon and start our api server here just on localhost port 3500 we've got our message connected to mongodb servers running on port 3500. i'm going to use thunderclient to test everything out like i have in some previous tutorials if you don't have it you can install thunderclient as an extension and then it's right here after you have on the left i'll click that i've got some collections and under auth i should have a registration route to test and now i'm going to hide the left hand menu over here because it looks much better and it's easier to read when it's the full screen so here's the register route see what we're sending in the body okay i've got a user named steve1 to create and then it's got a password and that's really all we need to send let's see if the register route works new user steve one created and here's our object in the console so now we can see what we've got username steve1 the role was created with user 2001 we've got our encrypted password and we've got a new object id and then notice this other field as well that's always added the two underscores and the v and the zero you should always see that as well if you're curious the v is the version key and it keeps track of this and we can also increment this manually if we want to okay now that we created steve one let's create another user and i'm gonna go back to my walt one that was an admin previously so let's create him as well and now new user walt one was created and if we look here in the console we can also see that one was created down here and here's his information now let's go to mongodb and inside of mongodb we can check our company db here and we should be able to refresh and now we have a users collection as well and you can see it has two documents so let's look at the users collection all right we load the documents up and here are the two records or we could call them documents really i'm used to saying records with sql this is a nosql database and it has collections instead of tables and it has documents instead of records so in either one of these we can expand the object and see our user 2001 that was created so we want to make walt an editor and an admin so inside of mongodb here we're mongodb.com and logged back into our account and we're looking at our collection inside of the companydb database that was created and we'd created the employees collection before but we had not created users so when we created the first user it also created the user's collection which is interesting but after that we want to edit walt here and we can do that right inside of mongodb.com so let's edit and now let's go ahead and add another role add field after user and we'll put in editor and the value for the editor was 1984 okay now we've completed that now let's add field after editor and we'll add admin and the value for the admin was 51.50 if i remember correctly and so now we've gone ahead and changed that information but we still need to click update here to update the document now the document is updated and walt has all three roles in his document oh but notice what happened here and you want to catch this if you do it because i certainly just made the mistake this was entered as a string and this should be numeric data so we want to get rid of that we don't really need to remove that we need to change the data type over here on the right notice how user 2001 is int 32 so we want to choose that type here on the right and make sure we have the right data type as we make changes here on mongodb.com to any given document okay those changes have been made now let's update and now we have the correct data type in walt's roles 2001 1984 and 5150. okay going back to vs code and i'll close out of thunder client and close out of the terminal as well but let's go ahead and show the file tree because we have changes to make in the controllers we need to go ahead and implement our user model instead of the json file we've been using in the refresh token controller the logout controller and the auth controller and then we need to implement the employee model in the employees controller and change how some of this works just like we did in the register controller and that's what we'll be doing in the next tutorial but my challenge to you is before then go ahead and make the changes on your own and then compare to the tutorial that i release that makes the same changes remember to keep striving for progress over perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 972
Rating: undefined out of 5
Keywords: How to create MongoDB Schemas and Data Models, mongodb schemas, mongo schemas, mongodb data models, mongo data models, mongodb data modeling, mongo data modeling, create schema, create data model, schemas, data models, mongo, mongodb, mongo db, what are schemas, what are data models, schemas in mongodb, data models in mongodb, how to create a schema, how to make a schema, how to create data models, how to make data models, data, mongodb documents, nosql, mongoose tutorial
Id: jZ-dzj6ut54
Channel Id: undefined
Length: 21min 28sec (1288 seconds)
Published: Tue Oct 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.