MongoDB MERN Stack Tutorial | MERN Project Data

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
the letter m in the mern stack traditionally stands for mongodb and our mirnstack project needs a mongodb database and data models [Music] hello and welcome i'm dave today we're adding mongodb to our mirnstack project i'll provide links to example source code and all resources in the description below mongodb is a nosql database built with collections of documents my node.js course gives a deeper explanation of mongodb and i highly recommend that course as a prerequisite before you complete this tutorial our starter code today is available in the course resources it's the completed code from lesson two as we now begin lesson three in this mernstack project series we will be integrating mongodb into our rest api today but before we do that there's a dependency that i want to set up in our existing code you can see i've got the package.json file open here i'm going to change the name to lesson three and go ahead and save that but afterwards i'll press ctrl on the back tick and i'll pull this down a little bit so we can still see the dependency list or at least some of it there i'll scroll that up there we go and i'm going to type npmi dot env and hit enter this is going to install the dot env package it doesn't take long and now you can see it listed in the dependencies this will let us use environment variables inside of our rest api now environment variables are values that we want to use on the server when we deploy as well but we will not want those stored in github so we'll set all of that up let's first start by going to server.js and i like to put this right at the top the very first line and i'm going to put require dot env and then after that i need to put dot config and that allows us to use dot env throughout our package we won't need it in every file we'll just put that right here and we'll still be able to use environment variables in all of the files where we need them okay after doing that let's create a dot env file now it needs to be at the same level as the server.js here so i'm just going to create that file and it starts with a period instead of the word dot and then it's env now you can see i'm using vs code icons extension and then it gets this little gear symbol here and now we can put variables inside of here that we'll be able to pull out as environment variables so just as an example of this i'm going to type node underscore env and set this equal to development note i don't need any quotes around development or anything else this is just how you set them you typically set these as all caps for these environment variables as well so i'll save this and now back in the server js somewhere here and i'll just put it right towards the top i'm going to say console.log and now to pull a value out of the environment variables i'll say process.env and then we put the actual name of the variable so i'm going to log that value to the console when we start up our server so let's go ahead and start up the server i'll do control backtick then npm i want lowercase here npm run dev and i'll pull this up and let's see what we get inside of our console and i had to scroll to see it there so the development was printed before we got the server running on port 3500 but there is our environment variable printed to the console just like we expected it to be with the console log statement so now to keep this value or any values we store inside of the dot env out of github we want to make sure to list that dot env file right here inside of the git ignore file as well okay now as we set up our free mongodb.com account we're going to get a database uri string back that will let us connect to mongodb and we'll want to store that in this dot env file so i'm going to put database underscore uri equals and this is where we'll put the connection string that we get from mongodb so the next chapter of this video is about five and a half minutes i've got timestamps in the description and it's going to walk you through setting up a mongodb database at mongodb.com now this clip is taken directly from my node.js course because the process for setting this up hasn't changed at all so just as you go through realize this about this mirn stack project that we're creating you can name your project whatever you want but please name your database technotesdb and i'll type this out just so you can see it so remember to name your database as you set this up as tech notes db with a lowercase t at the beginning at least if you want it to match my code so you'll have that and then create your first collection and call it users all lowercase now i'm going to go ahead and share that clip so you can go ahead and create your mongodb account if you already have that if you already know how to do it just skip this chapter in the video and we'll come back and we'll put our database uri right here inside of the env file okay we're at mongodb.com and i already have an account so i'm going to choose sign in if you don't have an account you'll want to sign up for a free account so you can just click try free i'm going to click sign in and then it will take me to a page that probably uses my google id or allows me to log in with an email address yes there it is so you get those options i'm going to log in with my google email address or my google account and then we'll meet back up after you have your account or you've signed into your account okay i'm signed into my account and i'm on the projects page where i can create a new project and you see i already have one project here now if you're not on this page once you're signed in just click the little leaf in the top left and it says view the organization home because that's where this is so once you're there you'll want to create a new project and now you want to name the project i'm just going to name this one tuts short for tutorial and click next and then it asks you to go ahead and set permissions or members and it'll probably assign that to your default account to start out with as you can see i have project owner right here so i'm going to click create project with the project created you can see i now have tuts up here above database deployments we need to build a database and of course it gives you the big shiny button right in the middle to do so so please click that and then it gives you choices and we're just going to go with free today if you want to get one that you pay for that's fine i'm going to choose free over here on the right and then it will say create a shared cluster and right now i'm just going to keep all the defaults so free shared it has aws it has one of the usa regions for me because i'm in the u.s you may want to pick a different one if you're not and maybe it already defaults to something close to you and then it just has these other default settings and i'm going to go with all of that even the default name here cluster 0 and click create cluster at the bottom now it says new clusters take between 1 to 3 minutes to provision so i'll come back when this is finished my cluster 0 has now been created and we're given this screen so what we want to do is click browse collections we don't have any collections yet so we get this and it says load a sample data set or add my own data we're going to choose add my own data with that it asks for a database name and a collection name so let's just call this company db and then we can call the collection name let's go with employees and i'll just keep that all lowercase companydb is capital company and capitaldb at the end and i'll click create and with that has created our company db database and our empty employees collection right here what we should do now is concern ourselves with database access so let's create a user that can access this new collection and database that we have so create a database user we click the big button that says add new database user and then it gives us password certificate and all of that we'll just stick with password and it put in some old information for me let's put in something different here let me go with tut once again and then for a password i'm just going to and we'll go ahead and show whatever the password is i'll go with testing one two three kind of like a mic check okay so we've got tut testing testing123 i think we'll keep all of the default options here and we want the read and write to any database and of course i'll come back later and delete this user but for now we'll use it for the tutorial and we'll click add user and once we have the user we need to go back to our cluster so let's click tuts and that takes us back to our cluster and it says we are deploying your changes current action configuring mongodb so i'll give this just a second and then we're going to click connect with the configuration now complete let's go ahead and click the connect button it tells us we need to set up some security this part is required and what we're going to do is allow access from anywhere we don't really know where we're going to host our back end yet so this is good for development right now until we actually know what i p address we had so let's just add in the zeros and that means it's good from anywhere we already created a user so now let's click choose a connection method and we're going to connect our application this gives us a connection string and this is what we want notice it's already put in the tut user i created now i'm going to have to put in the password including getting rid of the less than and greater than around the password and then also i need to replace my first database with the company db which was the name we gave the database so i'm going to copy this and we're ready to close out of this now and open up visual studio code okay you should now have your connection string from mongodb i'm going to paste mine in here except i'll show you a difference i'm going to press alt z to get this code to wrap you should have your username right here and then you should have your password right here of course i'm not going to show you mine but here just in a second as we go away from the screen i'll put mine in so mine continues to work as well as we connect to mongodb notice i also have the tech notes database name right here inside of the string as well so you can just match that pattern up to yours to make sure you have a proper connection string from mongodb we're back at the package json and we're almost ready to create our data models but before we do that we need to go ahead and import in one other package and that package is called mongoose it's a library that really helps us communicate more easily with mongodb so i'm typing npmi mongoose and installing that as a dependency as well it won't take long either i can close out of the terminal and we'll now see mongoose listed here amongst the dependencies as well so now in the file tree i want to create a new folder and we'll call this folder models this will store our data models and now inside of the models directory i'm going to create a new folder and i'm going to call this use i said new folder a new file and i'm going to call this user.js with a capital u and this will be our user data model the first thing i need to do is require mongoose so i'll say const mongoose equals require mongoose after that we'll start creating a schema that will allow us to have a data model and so we'll say const user schema and we'll set this equal to a new mongoose dot schema and now that schema has a capital s when you put it after mongoose and the dot okay inside of our user schema is where we'll have our data model so we need to think about the different types of data that a user needs to store let's go back to our user stories quickly and we can look at some of these points in here to see or get an idea of what data our user needs now of course we need a username and a password but let's talk about the rest let's look at number 13 for example says users can be employees managers or admins so we also need user roles and then let's look at number nine and it says provide a way to remove employee access as soon as possible if needed and really we should switch this to user access and then underneath that number 10 says notes are assigned to specific employees that's true but employee refers to a role really so let's also say to specific users now this won't impact our data model for user but it will for notes but we just got the terminology defined a little bit better by switching employees to users there so what we do know is we need roles as we see here in number 13 and also for number nine provide a way to remove user access asap if needed let's give an active status and that means users might be assigned to different nodes and we wouldn't want to delete a user if they still had notes assigned to them so what we can do is disable a user by having an active status basically boolean data if they're active true and if not false and that would allow the admin or manager to remove user access asap if needed okay with those changes made to the user story and we've gone over that a little now we're ready to define our model so we'll say username that's the first thing we need and then this is an object as well and here we'll say type and this will be string type data and then we can say it is required and we set that to true now after that let's put a comma and then i'm just going to highlight this and do shift alt and the down arrow and i'm going to switch this to password and it's also string and also true now let's do that once again shift alt and the down arrow and we can put roles but now we'll make another change here let's wrap this object that we have in an array so we'll put our opening bracket and our closing bracket and now we're saying roles is an array and the data within the array will be string but instead of required let's put a default value and we'll have the default the employee so even if a role is not assigned in our front-end application as the request is sent to create a user it will assign the default role of employee now as an array this indicates that a user might have more than one role and more than one value could be stored of course in the array now we could copy this down one more time so let's do this again with shift alt and the down arrow and here we'll have an active status let's go ahead and remove the array from around this we can remove that final comma because this would be our last one now the type here will be boolean and then we'll have a default to true as we would create a new employee they should immediately be active without us even needing to send that data to the api this will just allow any new employee or i should say any new user created will automatically be active now before we finish with this file we need to come underneath the definition of our schema and just say module.exports set this equal to mongoose.model and then we name it user and then we pass in the user schema that we just created and now we should be finished with our user model and now we need to create a note model i am going to just ctrl a to select everything in this file and ctrl c to copy and then create a note js with a capital n and i'm going to paste everything in from the user model and just make some changes but before we make those changes i guess i could make the first one just so we know we're working with the note model we'll change this user schema and i'll press ctrl d to select the second instance of that and then i'll move to the front arrow over 4 and change this to a note schema other than that let's see if we need to change anything else quickly just the name here of the model we can change to note and now as we come in and make changes to these different types of data we once again want to refute refer to the user stories let's look at 10 11 and 12 so notes are assigned to specific users so we know in this note model we need a reference back to the users and then notes have a ticket number title a note body you could say the text of the note and then created and updated dates and then notes are either open or completed so this is another status here we could basically say it's completed or not and if not it would be open so those are things to consider as we look at what data we want to store in the note so let's start out with a user because we know it needs to refer back to the users that we have now this data type is going to be just a little different than string or number or any normal type of data that you would think of this is related to mongoose so we'll say mongoose dot schema so we're referring to the other schema we've created and we say types and we say object id well we're not specifically referring to that other schema here but we're saying what type of data this is it's an object id from a schema then required is true but one more comma after that and now we have a ref here now this is where we're referring exactly to which schema so this is referring back to that user schema that we created after that let's change password to title this would be type of string and true after that we could change this one let's call it text because it is the text of the note and this would be string and let's put required true again for that but we also need to remember to remove the array that is wrapped around this one as this was roles in the one we copied from okay after we get text oh i've got an extra quote there okay after the text now we have the completed and this is a boolean again but the default will be false because when we create any new note it will be open and not completed so we needed the opposite right there now those are our basic data types but notice it's not all of the data types we needed we also said we needed dates both created at and updated at and we need a ticket number so there are some other things we're going to do for those types of data i'm going to move the curly brace off this top line likewise off this bottom line because for the time stamps we need to add that is an option so i'll put that on a separate line and then inside of here we can just say time stamps and set that to true and mongodb will actually give us both created at and updated at time stamps just by setting this option and when i save you'll see it gets formatted just a little differently but this is easier for me to read to know that this is one object and then this option here is another object so now we have everything except our ticket number that we need for the note and really there will be an automatic object id created with every record and that's what we're referencing here for the user and the note will have one too but as you may see this as we work through the mongodb object ids are very long strings and it wouldn't be too practical to use that for a ticket number and in fact what our owner dan d wants is a sequential ticket number now he doesn't want it to start at zero because that makes it seem like his shop just opened up so he said started at 500 or higher and that's what we'll do but then every note created will be in a sequence of ticket numbers we can do that once again by installing a package that will help us so let's go back to package.json so we can see it installed and control and backtick and then let's say npm i mongoose dash sequence and this will install and then it will help us issue those ticket numbers in a sequence okay we know we have the dependency now so now let's go back to the note j s model and at the top of the file we're going to define auto increment and we're going to set this equal to require mongoose dash sequence and then after that we need to follow it with another set of parentheses and pass mongoose in i know that looks different than some requires you may have seen but that is what is documented for this package okay now we'll scroll down to where we have created our schema here already so right after the schema we need to say note schema dot plugin and then we pass in auto increment put a comma curly brace and we set some options for this so now we tell it what the increment field is going to be named and we're going to name it ticket this will create a ticket field inside of our note schema and that will get the sequential number this also gets an id called ticket numbers we won't see this inside of our notes collection what will happen is a separate collection named counter will be created and we'll see that id inside of the counter collection and then we need to tell it what number to start the tickets at so we'll say start sequence which is just seq for this option and we'll tell it to start at 500. now that's all we need to do and once we start creating notes this plugin for auto increment that we're using from mongoose sequence we'll create a separate collection called counter where it tracks this sequential number and continues to insert it into our notes we have now created our models and we have our connection string inside the dot env file so we are now ready to create our connection to mongodb let's go to the file tree and the config folder and let's create a new file in the config folder and i'm going to call this db and then a capital c o n n so database connection dot j s we'll start here by requiring mongoose once again so we'll say const mongoose require mongoose after we do that we'll just define a function called connect db this will be an async function and inside this async function we'll have a try catch inside the try will await mongoose dot connect and then we just pass in that environment variable so process env dot database underscore u r i and then we'll have our catch and here we'll just catch the error and then we'll console.log the error that just should be err there we go after that we can do the module dot exports set this equal to connect db now we're ready to go back to the server.js and we'll start here at the top with a few more imports we need to import connectdb that we just created so this will equal require and then we'll be looking at the config folder and then we should be able to look at db con there it is we'll also need to require mongoose here so we'll say const mongoose equals require and get mongoose there it is and then after that i want to go ahead and bring in that log events function that we have inside of our logger file so this will equal require and then it's inside of our middleware folder and then it's inside of logger so now we have our three imports we're ready to apply these to our server.js we don't have to scroll far let's just go right under this console log where we logged the node env value and let's call this connect database function and then we can scroll all the way to the bottom where we're listening for the port and saying the server is running on port and providing the number we're going to wrap this in a listener for the mongoose connection so here we can say mongoose dot connection dot once and we'll listen for the open event and then this has a callback function and we'll put our app.listen right inside of here and then we can put another statement as well so first i'll paste this one in but also let's go ahead and console.log connected to mongodb now i'm going to scroll for just a little more room and we can put one other listener here so this will be mongoose dot connection dot on instead of once and we'll listen for an error so if there's an error with our connection then we'll pass the error into this callback and then we could console.log whatever the error is let's also use our log events and i'm going to paste this in once again just so i don't have typos it's a template literal and just always create some typos as i try to type them out so i'll spare you that but what we can get from this is the error number the error code the error system call and the error host name all of that should be provided through a mongodb error and then we can create a new file called error log dot log and i'll save the file here now one way you could test this is to go ahead and stop your internet connection and then start this server remember you would type npm run dev and you should get an error here i believe it doesn't provide an error number so it'll only do that if it's available it might say undefined there but i have tested that out and you get everything else written in your error log and the log will appear in your logs folder as expected now we're going to test out all of our user models we created and everything about our mongodb connection as soon as we create controllers to process the rest of the crud events the requests we'll get the create read update and delete so that is coming up next for now let's just open up a terminal once again type npm run dev and we'll make sure our mongodb connection is working as expected starting the node server we've got development from our environment variables it says connected to mongodb and the server is still running on port 3500 everything is good to go 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: 22,151
Rating: undefined out of 5
Keywords: mongodb mern stack tutorial, mongo, mongodb, mern stack, mern stack tutorial, mern tutorial, mern, mongodb mern, mongodb tutorial, mern stack project, mern project, mongodb project, mongodb data, mongo mern, mongo tutorial, mongo data, mongo project, mern stack data, data, mern stack project tutorial, data layer, mern data layer, mongodb data layer, mongodb connection, data models, mongoose, mongodb mongoose, data schema, mongoose tutorial, mern mongoose, mongo db, database
Id: cUV3uYXEOxI
Channel Id: undefined
Length: 29min 36sec (1776 seconds)
Published: Fri Aug 05 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.