Node JS with React and Mongo DB (Mongoose Database) | Node Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey coders welcome back to another node project this time i'm going to continue with my node react project that i did previously and i'm going to connect a database to it so if you want to follow along you can download my code from github.com but if you don't want to you can completely follow this by just watching the video and i think you should be okay with understanding how databases work with node and react so let's go ahead and finish up this project okay so starting off right here i have visual studio code open if you remembered from my previous project we were working on in our sandbox using node react app this is the previous project i'm going to copy this copy three items and put it into a new folder called node react mongodb app so let's go in here and paste it in you can also get all of my files here if you go to my github under github.com kodakai slash node react tutorial and you can copy the same files and follow along with this tutorial but if you don't want to copy these files is totally fine you can start a brand new project and i will show you how to do the database part and you can probably pick it up through there okay so what i'm going to do next is drag this whole node react mongodb app folder into my visual studio code and i will hold ctrl and tilde to open up my terminal down here because we need to go into that and the first thing we'll be concentrating on is the back end so before i get into the coding here we need to set up our mongodb database on the cloud so let's go ahead and do that i am going to head over to mongodb.com right here mongodb.com is a free website it will allow you to create databases or collections they're also called clusters and everything here is free and it's totally fine to do testing on so go ahead and click on try for free but i already created an account so i will log in through my account right now all right so once you've created your account you will see a screen that looks like this and i will step you through the very important aspects of this first and let's get you set up the first thing that it might ask you to do is to create a cluster if it asks you to create a cluster go ahead and create one otherwise there's a button over here called create a new cluster because you will need to create a cluster first but after you create that cluster let's go down to database access so we can set up our permissions first you'll notice that i have some logins already but i will create a new one so you can follow along for this example project so add new database user and i suggest right now to use a password for this example i'm going to give this username ego thing and for the password i'll show right here sensei now i really suggest that you use this auto generate secure password i am setting it to read and write to any database for this one now this is going to be a temporary user for me i also love this aspect about it i'm going to set it for one day so that i don't remember to remove this permission after i'm done with this project and upload this video so i'm going to add the user and the next thing i want you to do is to go down to network access right down here you'll see that i added an entry for an ip address right here so mongodb.com is very secure they may not allow you to log in through your database access through our code if you do not add this ip address i added this so that i can access this database from anywhere so go ahead and copy the same thing right here for the access list entry put 0.0.0.0 and what this does is it allows anyone to log in through any ip but if you would like to limit to your own ip only go ahead and add your own idp address so that no one else can log in or try to log in and that's going to do it for the security aspect of it so let's go back to clusters now click on this connect button right here and it has a couple of connection options go ahead and select connect your application and what we want to do right now is copy this string right here we will need this for our coding so that we can connect to this database so go ahead and click command copy and open up a text pad i like to do this create a new document and then i'm going to paste in this string right here and we'll go back to this in a minute i'll just minimize it right now and once we get to our coding we'll add in that string now here's the fun part let's go to the collections next you'll notice that i created my cluster called node cluster you can call it anything that you want and you notice that i created a couple of databases already they also will give you a lot of sample databases so that you can look through them i really suggest looking at the sample mflix as an example to see how to create tables in here or otherwise called collections and documents but we will be creating our own database right now for our project for our twitter clone project if you remember from our previous project we were doing a twitter thing so go ahead and click on create database right now and i'll be calling this node twitter clone and for the collection name right now i'm only going to create a users table to give you an example so you'll see right here it created my node twitter clone with a users collection and if i wanted to create another collection i can click on this plus right here so go ahead and do that because we also need another collection called tweets so go ahead and create that these are basically tables if you remember from mysql type tables just think of these as tables now for the users i'm going to insert some documents so with mongodb it uses a thing called documents and i really suggest that you read up on mongodb mongoose database and how to use documents but what i'll be doing with this tutorial is stepping you through all of the basics and you should get a handle of things once you see this whole tutorial but right now we'll do an insert document and you see right here it automatically generated me an id because if you worked with my sql database tables you'll know that we always need an id with every table right now i'm going to create something called a username field and i will give it a username of coder kai and then if you click down here at this plus sign you can add another field right under username and i'm going to give this a name a full name and this will be a full name of coder chi just like that and then also i will create another one called entry date and right over here you notice there's selections for what data type it is i'm using string for both of these but for this entry date i'm going to select a data type of timestamp so every time a new entry comes in it will automatically timestamp this for me so let's insert this right now and there we go i have my first document data inside my table users right here and you'll notice that it generated me an object id so this is very important i'll step through it in a minute when we are inserting documents into this table so that's all we're going to do with the mongodb right now i wanted to show you how to add things into the table but for the rest of this tutorial i'll be doing it through coding on inserting data and retrieving data so let's jump into that okay so back inside our visual studio code and right now in my terminal i want to cd into my back end folder right here because we are in the main folder you'll see right here i list it out back in and front end so i want to cd into our back end and first off i want to show you my node version so here's node v version 15.10 and i'll also show you my npm version npm.v and is 7.5.3 so now that i'm inside the backend folder i need to install our mongoose database and what we do is type npm install dash dash save mongoose so i'm installing this into the back end folder i will also need to install something called a dot env so do a npm install.env and if we check out our package.json right here you will notice that i have emv version 8.2 and mongoose version 5.12 the next thing i want you to do is inside of backend create a new file and we are going to call this period env so a dot env file and this is an environment file that we can access so now going back to the connection text file right here with our connection database string go ahead and copy that and then inside of our dot env file i'm going to give it a d db underscore uri with our string and let's fill out this string right now right here is asking for our user name so this is the user that we created called eagle thing and the password sensei now is accessing my cluster right here yours will be different and then right here where it says my first database this is where we need to add in node twitter clone because that is the new database that we set up right down here i'll also create something called a port and give it 4000 and i'll show you how to use this right now let's save this file and then let's open up our index file inside the back end alright so let's include our mongoose database cons mongoose equals require that's right mongoose and then we also going to require the dot env config so this will include the env file that we created down here you just have to type it like that you'll notice that inside of the emv file i gave it a port 4000 so let me show you how to configure this now instead of telling it you know const port like that i can now access that environment variable by saying process dot env dot port or if you can't find it or just add four thousand to it so that's how we access parameters that we set inside of our environment file right here so let's go ahead and set up the mongoose database right down here db connection and how we access it is by calling mongoose.connectprocess.env.db uri so that's the string and for the rest of this you can just copy it how i'm typing it give that true and use unified there we go true this is not something that you'll need to remember just go ahead and copy and paste it then so if it made the connection i'm going to console.log this and say db connected to let us know that the database successfully connected now if it didn't i'm going to catch that error error arrow function let's close that up and console log that as well error let's go ahead and save that and there you go you've successfully connected to our mongoose database so this environment file is now done so i'm going to close it out and what i'll do is i have some other database connection code that i will paste in here it's not really necessary right now but what i'll do is i'll paste this in so that if you're working on a production code you can use this and this is how it uses it in production but right now we're not in production so i'm going to comment it out but i will leave this in the coding for you to access and use if you are building this code for production and how it knows if it's in production i have an environment right here called node environment so i forgot to add that in let's do node environment right here node env equals and we're just going to call this dev right now so if you're going into production just go ahead and put production like that and it will know to pick it up so right now we're just in development so save this close it back out but right now i'm going to comment it out because we're not using it and that's going to do it for the index.js go ahead and close that up so let's go ahead and test out our server right here to make sure that it's making a connection so npm run server and right down here it says server is running on port 4000 and the database is connected so we are fine with that go ahead and cancel out this next up go up here and i want you to create a folder inside backend called models and inside models i'm going to create a file called schemas dot js and inside the schema file i need to define our data structure for our tables users and tweets that we created so in here let's include the mongoose and let's also create the schema schema so that's how we defined that and right now i'm going to set up the user schema so let's do a const user schema and we're going to do a new schema and i like to close this up and right in here that's right we're going to define our fields we have a username and this is a type string and it is required so anytime we create a new user it is required to have a username right down here full name this is also a type string and i don't have to make this required but i will make it require just you know if you don't want to you can just omit this and just have it a type string and then we have an entry date and this is a type date and right here i can make a default to the current date dot now so anytime a new user is added it will add the current date and time to it you'll notice that i didn't create a field called id and you've seen that when we created that new user table inside mongoose and it is an object id because this will automatically be created every document we create mongoose we'll create an id for it next let's do a const tweet scheme and that is a new schema close it up and we just have a tweet in here and that is a type string and it is required and i'm going to do this down here i'm going to call this user this is a type schema dot types dot object id and let me explain this it's referencing the users table so what am i doing here if you worked with mysql tables you notice that you will need to do some inner joins and joining tables together so basically when i am going to query my tweets i am going to reference that to a user and at any time this user gets an updated username or or their name it will just reference that table so this is how we do it it's the same thing as if you remember sql syntax it's like select you know from a and then you do an inner join b on you know a dot id equals b dot id so it's that same concept right here where i'm i'm joining this together to reference the user and same thing you notice that there's no id up here it will create it on its own and that's right anytime we reference a table it is using the object id of that table so that automatically gets generated by mongoose and you see we're referencing it through the id and then down here let me do a const users notice that i'm using uppercase here for users this is a different variable here and i'm calling it mongoose.model users this is the name that i'm giving it user schema i'm referencing this user schema right here and calling it users and now i also need to create one called tweets and i'm going to reference the model for the tweet called tweet schema tweets and then now i'm going to do this down here and i'll explain why my schemas equals users and i'm calling the users right here this name right here and i'm telling this to be tweets and i'm calling the tweets so why am i doing this right here when i first worked with schemas i didn't know how to export multiple schemas and so i found out how to do it by combining it into a variable called my schemas and then now you can do a module dot exports equals my schemas otherwise you can only export one so that's how you get around it you can create multiple models now of these schemas put it together under one and just export that so go ahead and save this we are done with our data structure i'll keep this open as i move on to our handler here so you'll remember that we created a routes handler go ahead and open that file up and inside our handler you'll see that we have a tweets and this is just url routing for our handler and we have an add tweet so guess what we're going to populate our ad tweet now and i'll create a few functions to show you how to insert and then to retrieve so let's get into this okay so to start off we need to include the schema of course so let's const schemas equals require and let's go to our models folder here schemas digest now i'm going to create a new router right here let's do a router.get and this will be add users add user request response arrow function let's close it up and if you remember earlier i manually added a user inside our user table right here i manually added coder chi right here but right now i want to show you how to add it through code so i'm going to create this right here and i'll just give a string right here user equals username it's going to create this object called eco fang and full name sensei johnny because i'm going to add this into the user let's do a cons new user equals new schema dot users so right here we have our users and i'm going to insert the user right here that's what i'm inserting to the new user and so let's do our insert for this i'm going to try it and i'm going to do a a wait on this because we need to make sure that it goes in there and we need to wait for it new user dot save and this is going to be an async error new user result arrow function and let's close that up so since i am doing and a wait right here you notice that i'm i need to declare as an async so i also need to declare it up here as asynchronous right here when it's been created i'll just console log it and say new user created and then i'm going to respond dot end on this and this will show to our screen right here and end the process now we also need to catch any errors and if there's an error i'll just console.log it for now and also response.end user not added to let myself know that something went wrong there we go and i think i also forgot a bracket right here there we go and let's see here i also have an extra bracket right there remove that sorry about that guys always check your typing for syntax errors save that up i believe i have no problems now and let's do a npm run server and here we go database is connected let's open up our browser and it is 4000 for our backend and so let's call up add user and there you go new user created how do we know let's go over to our database here and let's refresh the users table here and there you go you'll see that we added through coding a new user eagle thing and sensei johnny so that's how you insert users using the back end coding let's close out this server right here and so this was only an example to show how to insert it so i'm going to comment this out right now and then i'm going to focus now on inserting tweets and retrieving the tweets and i'll also create a a tweet form where we can submit the tweet and it'll insert it into our tables for us so i'm going to scroll down here and if you remember i have this router post right here called add tweet and we haven't added anything to it so let's go down here and add to it and what i'm going to do is if you notice up here how i did it add user you notice that this was a get and it was just a simple static way for me to add a user you notice that i created a string with my user but now we're going to add it through a post and you'll see in a minute i would create a form with a simple input box for a tweet with a send button and when that button sends the tweet it will send to this router right here to post it and so i will grab that by saying const user tweet equals request the body and i'm going to get the tweet input field because i'm going to call that input field tweet input the name of that will be tweet input so this is the same for forms if you worked with it before through html and other ways of posting a form and then now since i got this tweet input i can do the same thing like adding a user but this time adding a tweet so let's const new tweet equals new schemas dot tweets close it up and inside here we have our tweet right so now we're using the user tweet so it will populate it with that and guess what we also have a field in here to link the user that's tweeting it right i am going to call this uh that field right here because i'll show you right here how i'm going to link the user id right here the user id parameter because we need to grab that user and i'll show you right now how to grab a user in our database so i'll go back to our schema right here and you'll notice that inside our tweet schema i have a field called user and that references the users table right here through the id so i'm going to use this right here through our tweet schema the user and that's why i'm calling it right here user and i'm telling it where to find that user by its id but i haven't gotten this id yet so let me get it right now and i will do a const user id equals and i need to do an await for this because i need to grab it and wait till it gets it and i'm going to do a find one this is a mongoose function to find a document inside our database so i'm going to find you can use any of the fields here i'm going to find it by username and i'm going to find my username called kodakai and then i'm going to execute that so this right here simply looks into our user database table and it's finding a username called kodakai and it's returning that id for me so if i go to my user table right here it will find the username code kai and it will re turn this id right here this object id for me because that id is linking to our tweets user table so now that this retrieved the user id for me i can populate it to this user right here and so you'll see that everything is now linked up with a tweet and who tweeted that now you can also ask why am i manually adding this in well in a real life situation when you're creating an application for a tweet page i'll show you later on when the whole program runs if you think about it like twitter you're logged in through twitter and twitter is holding this id for you already so it knows who you are but in my example here i haven't created a login where it's saving that id for me to reference so i'm just pulling it right now through this username but think of it and a real life situation where you're logged in and you already have this id and you can just simply populate the id to link the user together so let's go now and try to add it and i will do an away on this new tweet dot save and it has an error and new tweet results arrow function and remember this is asynchronous so i need to add async up here now if there's an error i'll just do a simple response dot end on and say error saving otherwise i will redirect our page back to the tweets page and i will end that you have to make sure that the page ends after you redirect it and then let's catch any errors and same thing i'll just console log it if it has an error and i'll just also redirect it back to the tweets page and response.end after i've added this right here you notice that i haven't defined user yet so let's add that in let's do a const user equals schemas dot user users there you go so now that is defined there but you know i will also modify this right here to now grab our tweets because this is static right here from our previous example so let's just remove all this let's remove our old code okay let's modify our tweets here and we know that this is also going to be an asynchronous function so let's just add async right here and let's cons tweets equals schemas dot tweets we need to reference that schema right here our tweet and then i'll give you some tips right here um if you are only going to query one table it will be like this user tweets equals await tweets dot find open close bracket and then you know catch the error and it will return the tweet data then i'll do an if error throw error otherwise if there's a tweet data and i'm going to make it really simple i'm going to do a response.end json.stringify and just return that tweet data so i can use it in our front end and parse it through else down here response dot end and i'm just going to end it if there's an error and of course you should do a little bit more better on this error checking right here this is just very simple right now so let me explain this right now you know that when you're selecting from a table let's use sql again as an example you're doing a select from table right and you're not doing any joins if you're selecting everything from that table it will return you everything from that table but in our case here our tweet also has the user that's referencing it that's attached to that it's we need to know who the user is that's tweeting it right so i can't use this right here i will change this now to user tweets equals await tweets.find open close bracket but now i'm using this function called populate and i wanted to populate the user because that's what i'm calling it right here user i wanted to every time i select from this tweet table to get all the tweets but i want it to also populate who the user is and reference that table so how you do that is kind of like a join where you're doing a join table a on b right so it's the same thing as that but i'm telling it to join this table user get all that and then i execute it and then that will return error and the tweet data just like that so now when this queries are table and finds all of my tweets it will automatically add in the user associated with that tweet okay so we're done with these gets in post right here for the tweets and add tweet so i'm gonna move on to the front end right now and tie together and show you the final results okay so let's minimize this back-end folder and now we're going into front-end right here but i'll leave these files open and inside front-end you'll remember inside of our source right here we have components and we have the tweets.js file so let's open that up because this tweet is the page that was showing us our tweets right and if you remember how it worked is that it fetches the tweet from the back end through our handler here it fetches it and then it iterates through it using the map function but now that we're pulling everything from the database i'm going to change some of this right here right up here under section i'm going to create a form now let's do a form method equals post and action equals add tweet that's right we are going to add a tweet form here inside our tweet form there's going to be an input that's a type text and the name right here this is important this is called tweet input and let me show you in a minute here let's do the input type equals submit we need the submit button the value equals send so we have two input fields right here we have one for the text to enter in our tweet and then we have the send button and i'm calling it tweet input so if we go back to handler here you'll remember that inside add tweet here this is where the tweet input comes from because i'm grabbing that from the body of it i'm grabbing that input field here to use so that's why we're calling it that now sorry about this guys because i am going to add some bootstrap coding to this to pretty it up but you don't need to if you just want to run this how it is it will just look a little bit funky for you guys but i have a little bit of bootstrap code that i want to add to it and this is just only going to pretty it up for me and i will also include this in my github if you want to look through it but yeah basically this is just bootstrap code to make it look a little bit more pretty bootstrap is a very nice thing to look into and learn because it makes things so much more simple to pretty it up instead of doing extensive css around all of these fields so that is my bootstrap right here i have a container and i added a header so that we can see that the page is called tweets and this is just a form with an input button and an input text field and then down here i need to modify this to match up with our with our new fields that we entered into the database so with my old bootstrap here i'm going to remove this bootstrap code right here and i'll pretty it up a little bit more but i'll just show you right here with what we're changing this to because we are iterating through our schema right here with our new data fields right here i'm now going to put everything on one line and i'll i'll call item dot we have a user dot full name write user.full name through the item because when we map it out you'll look at our database here and inside the user it has full name so that's how i referencing it through user item.user.full item.user.fullname so that's what i love about this map it just remaps everything very easy for you to reference and right in here i'll just say item.user.username how i reference that you'll see how this is formatted when i'm done and then we want to show the tweet and now the tweet is inside just item.tweet right and you see how simple that is let me just format this a little bit nicer i'm going to make this and i'm just going to add some bootstrap code into this so i'll be right back and then delete my old code here and you'll see that i have my new bootstrap code in here to make it look a little bit nicer all i'm doing is a row padding on it and then i'm using these alert boxes with a rounded peel effect on it and i'm just adding some little icons right here so you'll see in a minute when i run it and it looks a little bit nice let's save up this file and now we can run our front end and back in so let me show you the final product right here i'll add some tweets and everything down in our terminal here i'm going to initiate the back end server now i'm inside the backend folder so i'm going to say npm run server our backend is running right here database is connected and if you remember we can add another terminal right here and i will cd into our front end and now i'll do npm start for the front end that's how you initiate the front end server and you also notice that i prettied it up a little bit here the links are up here now now let's take a look at our tweets page right here you notice that we have no tweets in our database table right now so i'm going to add one i'm going to say i love node js and let's send that off and there you go you see it added the tweet for us so this is the formatted code that i have in the front end let me show you again where i have the full name username and the tweet and it's just formatted using bootstrap so here is the full name username tweet and then if i go to our database right here i'm gonna go to our tweets table here and you'll see right here it added to it you'll see the tweet field they have the string and take a look at this user is an object id that references this object string right here see this object string 604 f25 at the end let's go back to users here and here it is 604 f25 string so if i add another tweet with this different user it will have this object id for it but you'll remember that through our handler here i'm forcing it to find my username so let's step through all of this one more time i created a form with an input field and a button that when i submit it is this form right here with an input name of tweet input and when that submits it's sending it to this add tweet page where is this add tweet page it's in the handler the handler has the add tweet url right here and what it's doing is that it's looking for the user first and remember if we're just like twitter we gotta log in first to get our id but i'm telling it to look up my id using the username so i'll show you right here i'll modify this to be eagle thing for the username and so now if i save this it will look up that username when i tweet and reference that user with a tweet and what it's doing is it's setting up the schema for it the definition right here that we defined through this tweet and then it's going to try to save it to our database and then redirect us back to the tweets page right here the tweets url so let's give you another shot here let's go back here and now if i send off another tweet it will send it as eagle thing all right so let me do right here quiet and there you go you see how it just referenced the new one because i told it to look for the eagle fan user sensei johnny quiet quiet so yeah i hope you guys enjoyed this very intuitive tutorial right here this should complete this project for our node react project using mongodb i think with the next one i will step you through using uh another one called express handlebars to do um everything's very similar is just the front end is different because react is a different front end how you're coding it um pretty much react is using this front end right here with this syntax but there's another one that i love using it's called express handlebars i love using that one more the syntax it look is a little bit better but that's more for the front end but if you're looking to learn mongodb how to do all of the databases i really recommend using this mongodb.com to use the clusters with it read up on collections and documents how this works try to use some of these examples down here to do some joins because i showed you the basics look up mongoose functions on how to add remove update delete things save and i showed you the basics that a lot of people are using um that's very useful here on saving something on finding it and populating it by joining tables so just do some practice on this and you should get a handle of it but this was a very fun project to do for a very simple tweet clone and this project is pretty much complete i hope everyone enjoyed this coding project right here please give this video a like and subscribe to it because it actually motivates me to create a lot more programming videos for you guys and i'll see everyone in the next project tokyo
Info
Channel: Codr Kai
Views: 14,242
Rating: undefined out of 5
Keywords: node react tutorial, node mongodb tutorial, node react mongodb, node mongoose, how to connect mongodb with node js, how to connect mongodb with react js, react js, node js, mongodb, mongoose database, mongoose mongodb, node js programming, node js coding, how to setup mongodb, mongodb setup, mongoose db setup, node mongodb insert, node mongodb lookup, node mongodb connection, mongodb clusters, mongodb collections, mongodb documents, node js tutorial
Id: Oa0pMn0tvU4
Channel Id: undefined
Length: 42min 56sec (2576 seconds)
Published: Sun Mar 14 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.