Intro to MongoDB and Mongoose | 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 now mongodb for beginners tutorial series i'll put a link to the full playlist in the description below mongodb is the m in the mern stack it represents the database in the stack the front end application of the mirn stack is handled by react along with nodejs and express mongodb completes the backend rest api traditional sql databases are built in a relational structure related tables reference each other with joins as data is queried these relational tables also normalize the data that means data is not duplicated in the tables that's the dry principle which stands for don't repeat yourself and that's applied to the structure however with no sql databases like mongodb you can throw all of that out mongodb stores data in collections the individual records in the collections are called documents the documents have a key value structure and look a lot like json a collection holds all of the data about a user for example instead of breaking it into related tables and likewise duplicating and distributing the data where deemed necessary in a no sql structure is permitted so why choose nosql databases and what are the advantages of using mongodb performance is key the speed at which a collection is queried is very fast flexibility it's very easy to make structural changes like adding a new field without wreaking havoc in your total structure it is much like adding a new property to an object scalability nosql can support large databases with high request rates at a very low latency and finally usability as you'll see today we can get up and running with mongodb in the cloud very fast let's get started by going to mongodb.com okay we're at mongodb 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'll 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 us 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 one to three minutes to provision so i'll come back when this is finished my cluster zero 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 companydb 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 all of that will just stick with password and it put in some old information for me let's put in something different here let me go with uh 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 one two three 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 we're going to start with the code repository from the last tutorial in the node.js and express and now mongodb series but if you don't have it you should be able to easily follow along without it or you can download or clone the starter source code from the link that i'm providing in the description below so let's get started by going to our.env file and inside the dot env file it looks like i need to go to the end of the line and hit return so we have another line i'm going to create a database underscore uri and set it equal to our connection string but now we just need to replace a few things in the connection string and i'm going to press alt z here i'm using windows and it will wrap the code in visual studio code it may be different for you on mac or linux if you have those okay so we're replacing the password and if you remember i put in testing lowercase one two three and then instead of my first database we named the database company db now we can save this file because we're using the process.env to pull this value out when we need it to connect and speaking of dot e and v we actually put it in about three different files before and really we could have just put it at the beginning of the project it's not like when we require other things like the jwt here that need to go in individual files as they're needed this can just go at the beginning of the server.js so i'm going to pull it out of our middleware verify jwt dot js file and save that and i believe it's in a couple of controllers that we can remove it from as well but in the server.js file i'm going to put it at the very top you just want it in there as soon as you can get it and we'll save it and now i believe let's check these controllers real quick is it in the auth controller yes it is we can remove that and it's in one other controller if i remember right not the logout controller see if it's the refresh controller there it is and we can remove it from that as well and i think that will take care of it so let's close out of the controllers it didn't save the auth controller need to do that too okay close out of those and we're going to do some work here in the server well really before we do anything in the server we need to go to package json because we're going to install mongoose and i'm going to press control and the back tick you can also go to the terminal window or menu to open a new terminal window and here we need to install the mongoose package so it's npm i mongoose and return now mongoose js is a library that makes working with much easier kind of like you could consider react makes working with javascript easier than vanilla javascript it's just a helpful library so let's take a look at their page real quick it's mon goose there we go js.com we bring up that page and you can see it says an elegant mongodb object modeling for node.js perfect exactly what we need and it has some great documentation as well so we can refer to this as we go today we'll be working with a connection let's go back to vs code and see if our uh package installed it looks like it has so let's check our dependencies and we see mongoose listed right here on line 20 so we are ready to begin working with mongoose so now let's go to the server.js file and underneath credentials let's go ahead and require mongoose so we define const mongoose and set it equal to require and then we just bring in mongoose and save now after that we need to go ahead and create a connection configuration so as you might guess we're going to do that in our config folder that we have up here so i'll highlight that and click create new file and i'm going to call this lowercase db and then uppercase con so it's camelcase really db con dot js now let's start this file by requiring mongoose as well so we'll once again bring in mongoose and require mongoose and now we need to create a function that we're going to export and let's call it connect db and set this equal to an async function mongoose is async let's go try and after try we'll have our catch with an error block here and we'll just console.error and pass in the error and then up above we need to go ahead and try to connect a mongoose so how we'll do that is a weight we've already got async above and then we use mongoose and we choose connect and from there we need to bring in that db uri that we defined back in our dot env so we can just refer to process dot env dot database underscore uri and then there's an object and what we need to do is pass in a couple of options that will just prevent warnings that we would get from mongodb otherwise one is use unified if i spelled that right topology and we set that to true and the other one is use new url parser and we'll set that to true as well and then we should be pretty much finished except we once again need to do module.exports as we have many times before four functions we've created and exported and it is connect db and we can save the file with our function created let's go back to server.js now and we need to import that so say const connect db is going to equal require and then we need to go into config and from there we need to pull in db con and save and now let's go ahead and connect to the db the very first thing if it fails we don't want to listen for any other connections anyway so this is connect to mongodb and all we do is call connect db right here and it's ready to connect however there is one issue to address here so let's scroll all the way down to where our app listens for requests now we don't want to listen for requests if we don't connect and so if our connection fails for whatever reason we need to avoid doing this and we can do that let's go back to the documentation for mongoose and where we had connections here in the documentation we also have connection events and let's look we can listen for the connected event and there's also the open event which is equivalent to connected so let's go back to our code and use that and we can do that with mongoose which is why we required it for this file in particular and we'll have mongoose dot connection and then we want wants instead of on because we'll just listen for this event one time and we'll listen for the open event it's a little shorter to type than connected and now we'll have an anonymous function and inside this we can console.log first and inside there we'll just say connected to mongodb and after we've connected to mongodb let's just go ahead and cut and paste in our app listen and we'll put it right there and now we're only going to listen for requests if we have successfully connected because that is when the open event will be emitted by the connection and so then our console will let us know we've connected to mongodb and we're listening for requests on whatever port and of course here in development we are defaulting to port 3500 as set at the top okay all of that said i've left the terminal window open let's go ahead and type npm run dev and i'll drag it up so we have a little more room and let's see if we connect and we're connected to mongodb and the server is running on port 3500 okay in the next tutorial we'll create schemas and data models with mongoose and relate that back to our mongodb collections 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: 1,876
Rating: undefined out of 5
Keywords: intro to mongodb and mongoose, mongodb, mongo db, mongoose, mongoosejs, mongoose js, connect mongoose with node js, node, node.js, nodejs, connect mongoose with mongodb, connect mongoose to mongodb atlas, mongo, mongodb atlas, atlas, introduction to mongodb, introduction to mongoose js, nosql, mongodb node, mongoose node, nosql database, database
Id: -PdjUx9JZ2E
Channel Id: undefined
Length: 17min 6sec (1026 seconds)
Published: Fri Oct 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.