Node.JS Full Course (THREE HOUR All-in-One Tutorial for Beginners)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody my name is Caleb and welcome to your first node.js tutorial this is going to be all about writing JavaScript for the back end I also have a JavaScript for the front end a react series if you're interested this is going to bring you from being basically a complete beginner to having a proficient knowledge in writing JavaScript for node.js node.js made it to the top of the list for the 2020 stack Overflow survey being the most common web technology with react.js being a close second often these are used together node for the back end and react for the front end so it's a pretty in demand language and a great tool to learn one of the big reasons being if you just want to learn one language JavaScript you can build the front end and the back end of applications which can save you time and effort to maintain and build applications but fortunately a lot of the principals learned in node.js or other web Frameworks are going to be very similar so these skills will transfer to other languages as well so we're going to get started from complete scratch we're going to talk about how to install and initialize an application I'm going to be doing this on Windows but you can also use Mac or Linux it should be fairly similar once you have it open in editor the code is going to be the same now node.js can work on any platform so whether you're using Mac windows or Linux you should be able to follow along with this series now before we get started I wanted to say a special thank you to the sponsor of this series which is file stack you can get started with filestack using the link down below but this is a file uploader which allow you to easily transform and deliver images to users so it gives the ability to transform images if you have the need for the user to be able to modify images or for you to do it yourself and a delivery Network for Distributing these images across the web additionally we have some interesting features such as URL based transformations to easily modify images as well as conversion between different document formats and audio and video conversion as well so this easily integrates with JavaScript with an easy example right here so if this sounds useful to you check them out using the link down below to get started we are going to download node which you can get at nodejs.org so from nodejs.org you can go for either long-term support this is what's recommended for most users or the latest version for latest features I'll go with LTS so this is 18. if you're watching some future it might be a newer version once this is done we will open the file and go through the setup wizard nothing too crazy and I'm just going to keep all of the defaults and I'm going to automatically install necessary tools and then hit install give this a few moments and there we go as you can see it is installing some of the other requirements ah this is literally taking forever I'm gonna go run a marathon real quick all right I'm back and this is done so we will hit enter to close out of that and uh now you can actually open up Powershell or a terminal so we'll go with the command prompt here and you should now be able to say node and when you do this you will see a change in the prompt and now you just have this little carrot this greater than sign and this is the node interactive mode let me go ahead and zoom in a little bit so this is how we can interact with node in an interactive way where things are evaluated on the Fly such as five plus five you can actually see the response there automatically but if you enter it'll output that and then bring up a new prompt so this is an expression that evaluates to 10 we have the plus operator and then two operands five and five you can do something similar with strings so for example hello and then Plus there and I put a space there just so it turns out right and the result is hello there now notice the difference in quotes here you can use a single or double quotes interchangeably I'm just going over some Basics here if you wanted to have double quotes inside of your string you would use single quotes So for example hey there this will output the same exact thing we just typed but the actual string itself has double quotes in it now and the inverse two so if you wanted a single quote you could surround it with double quotes such as there so that is what you can do with single and double quotes and you can just go down to the new line sometimes I'll do this just to clear off the screen if you type something out such as console.log and inside of parentheses quotes hello and you hit enter you're going to get two things in the terminal here I wanted to explain this because as you're using this interactive mode you might see undefined show up quite a bit so with the fact that we're pretty early on in the series you might not have a ton of programming experience I'm going to try to explain this as simply as possible if you have something such as five plus five this is going to evaluate to some value and this is what is returned 10. some code does not return anything such as console.log and when that happens you're going to see the result undefined so don't worry about if you see that pop up it just means that no value was returned and it just so happens that console.log will also output the value hello because this is what we gave it so in that scenario you're going to see both of those values if we try another example such as math Dot p-o-w you can pass in a value here such as 5 comma 2. and what this does is it will take five and raise it to the second power five times five hitting enter you can see it gives us the value 25. so this is the return value here most lines of code are going to return some value but not all of them will so here is an example if we say let d and then assign this a new date this is a valid assignment this is going to return undefined this interactive mode as I've called it is also known as a reple read a Val print loop it's going to read our input evaluate it print the result and do that in a loop so the interactive mode is very handy if you just want to experiment with something try it out and you don't want to build out a whole project but oftentimes you're going to want to build out a more complex project that does a lot of things so that's we're going to be talking about in the upcoming videos how do we go from just the terminal to actually creating files and having a node.js project but always remember you can go back to the interactive node if you just want to experiment with things and try some different options it's a pretty handy tool so don't forget that it exists we might see it again throughout the series but most likely we're going to be working with files so let's get to that in the next video peace out welcome everybody to your second node.js tutorial this episode we're going to talk about how to take what we learned in the previous video the basic node.js commands and put those inside of a script so we're no longer going to be working in the interactive mode instead we will be working with a Javascript file so here we are in the command prompt I have the interactive node.js running to exit out of this you can do Ctrl C twice and now we are back to our terminal prompt now we're going to do is we're going to create a new Javascript file using a text editor or IDE whichever editor you decide to use that's fine because the JavaScript code is going to be exactly the same I'm going to be using the software Ultra edit which I'll also have a link down below for however there are many other alternatives for example Visual Studio code which many of you will be using as well whatever maybe we can just say file new and this will give us a new file and we'll say console dialog and inside of quotes hello world now this is very tiny so you can hold Ctrl and scroll in with your mouse I'm just using the trackpad on my laptop and that works just fine the software is also available on Mac for those of you who are interested so last thing we just want to save this as a Javascript file so file save and we can put this anywhere such as in documents we're going to end up making a project later so don't worry about location too much right now this is just an example so let's go ahead and just call this app.js and safe this will give us some basic syntax highlighting the layout is pretty customizable so if yours doesn't look exactly the same you can Tinker with view for example we have this document preview over here which will display an overview of the page so I could turn that off if I wanted with view view slash list and then document map and that will disable that easiest way to run this is just open a prompt either Powershell or the command prompt and then we'll just change directory over to wherever this is located which is in documents and then from here we can just say node and then app.js and we should see a response here hello world now that we have a basic setup to execute our node script let's go ahead and make a little bit more complicated of a script here I'm going to be going off of some of the getting started guide code so you can reference that if needed but basically what we're going to do is we're going to make a very basic web server to allow us to get some data to show up in the browser so to do this we are going to say const HTTP require and inside of parentheses we will say HTTP next we can use this that we imported to create a server so we'll say const server and this is going to be assigned HTTP dot create server and don't worry if you know you're brand new to node and you don't have all this stuff like memorized like I didn't have this memorized I had to refer to that page so it's no big deal the main thing is just becoming familiar with the different patterns of doing things and some of the different commands so we're doing in both of these lines is creating a constant kind of like a variable but you can't later change the value that's what this const means you could also see let or on occasion you might see VAR which is the older way of doing things and is not recommended so we recommend using const or let we'll go with const now this create server is going to require some data to be passed in and you pass in data inside of these parentheses it's known as an argument so we're going to pass it an argument is the way you would say it now the type of argument that it expects is actually a function or some section of code that is executed lots of new Concepts here especially if you're new to JavaScript but we have the ability to pass in a function that will be executed a function is just a section of code and we'll be using that word a lot through this series now we can define a function in line here with a set of parentheses an equal sign followed by a greater than sign so an arrow and then curly braces in this first set of parentheses we will Define two variables also known as parameters here which will be the request and the response which will have extra information about the request being made and we can describe what we want to respond to using this res parameter so if you think about a website the user is going to make a request to that website and then the web server is going to be like home somebody's reaching out to me what should we do let me take a look at that request see what they're asking for and then I can respond to that either sending them an HTML page or some Json data for an API or whatever it might be so that's what the request and the response parameters to find here are so make sure your code looks exactly like this so far you should have you know two parentheses here a single parenthesis here an open curly brace and then down here we'll have the closed curly brace and the Final close parentheses followed by a semicolon this structure will become much more familiar so don't get too lost in it right now don't overthink it just make sure it's typed out exactly as is now we can start describing that response so we can say res dot status code and set that equal to something like 200 which means everything thing went okay and then res dot set header and this is just to describe what kind of information we are giving back so you'll say content type inside of quotes and then the content type we'll be using will be Text slash plane and then lastly we will say res dot end and this is where we are going to actually say what the user gets back so let's go ahead and say hello world we are almost done after we Define that server we will just say server Dot listen this is going to take a port we will use 3000 and then the URL path or the hostname we will say 127.0.0.1 and then the final argument passed in here is going to be a function which will show up in the console when this server starts so let's define a function using parentheses Arrow curly brace open those curly braces and inside of here we can say console log and inside quotes server running like so all right so save all this you'll need to make sure you save before anytime you run your code and now it says server running from a browser you should now be able to visit 127.0.0.1 colon 3000 and this should show up as hello world which is exactly what we had it send as a response you could also instead use localhost 3000 these refer to the same thing now there was a lot of information but easily copy and pasteable from the nodejs.org website and this is just a basic way to set up a server now you could easily fill this in with different HTML so for example I could throw in here an H1 and then close the H1 inside of here I could say welcome to my page save this and over in Powershell or The Terminal we will close out of our running server with Ctrl C and then re-execute this server running and now when we go and refresh our page okay that did not work the reason this didn't work is because we actually have to change this to Text slash HTML and same idea we have to save restart the server and I'm going to teach you how to make this faster and more effective in the upcoming episodes now I'll give the page a quick refresh and this is actually rendered as HTML so that is how you could start building an HTML page and have the ability to do backend processing in node so that was a lot of information I'm sure especially if you're new but don't hesitate that was basically just showing how we can build out a server and get a script running now we're going to basically go back to the beginning and start building this up again but this time using a node.js project so this will allow us to install dependencies and have a more structure to our application versus just doing everything inside of a single node.js script with this we'll also talk about Version Control with Git as well as environment variables and all of the node.js things that you should be familiar with so stay tuned for the next video and hopefully this was helpful peace out welcome everybody to episode 3 in our node.js series if you made it through episode number two great because we basically just drank from the fire hose we started by creating a little server and if you've never done any JavaScript the code looked something like this it might have been a little bit overwhelming but in this one we're going to kind of start fresh we're not going to need any of this code so don't feel like typing it out if you're just jumping in this video we're going to learn how to initialize a node project which will allow us to have dependencies and various other things to build a more complex application instead of just having a single file like app.js we'll also learn soon how to create more rapid changes so I don't have to constantly stop our server and start it and just make things a lot better so from our terminal we are going to clear the screen and you can say npm which is node package manager this is included with node installed on your computer and then you can say init and there's an option we can pass in which is Dash Y which will make it faster but just go with this one for now uh just so I can show you what will happen after some time this pops up asking for the package name and basically if you use Dash y after npm init it'll do the default for all of these values so the package name default is documents because that is the directory that we are currently in the folder that we're in is documents so what I want to do is I want to actually cancel out of this with Ctrl C and what I want to do is I want to make a directory you can do that with mkdir and we will call this whatever our project is going to be about let's call it customers so let's go ahead and make an application for customers and I'll scoot this over a little bit so we can see so that created that directory and now we can change directory into customer and here is where we are going to initialize our project so npm knit and now the default should be customers so package name customers that looks good version description entrypoint index.js you could keep it as that or you could rename it such as app.js ignore the test command ignore git repository for now and basically just going to keep the default and it shows a preview of what that settings setup is going to look like and this is all going to be put within a package.json file so Json is just a data format where it's key colon value so key value pairs and yeah this looks good to me I will go ahead and hit enter for yes however if you decided to just go with all the defaults and not rename any things for example I change it from index to app you could just say npm init and then pass in the option Dash Y and then I'll just go with all the defaults and save some time but since I already did that we will just keep it as is so we have now is inside of documents we have a folder of customers and inside of here we're going to have just a package.json file and what we can do is we can actually open this folder inside of alternative so show more options or just navigate to this folder with whatever editor you were using so open this folder and now I have this open over here on the left in this file explorer so the package.json it's going to look like this where we have all those things we defined inside of this file and this is basically a way to say hey this folder that we're working in is a project if you're going to share this project with anyone then you're going to want to send them this whole folder and we're going to talk about how to upload it to Version Control and everything like that now you can actually change this file if you decide you want to change one of these values no big deal so I will often put my JavaScript files inside of a source directory and I forgot to set that in the entry point when we set up the application so no big deal we can just change our package.json and Save and what this means is we should create this app.js inside of a source folder so we can add a new folder call it source and inside of the source folder we can create a new file calling this app.js now in this file let's just do a very basic thing like console log and in here we will say hello world so the goal is to be able to run this so we can Define different run commands in this scripts section of our package.json so one of the commands is test which currently just says no tests specified so this isn't very useful unless we're doing some testing so I'm just going to remove it and instead what we're going to do is create a start command which is pretty common you can call it whatever you want so that's going to be inside of quotes there and then inside of quotes here we'll say node Source Dash app.js and Save now to execute this what we'll do is we will say let me actually clear this off we'll say npm run and then whatever our Command for our script is which in our case is start it'll eventually say what command we're issuing and give us the response hello world so that is how you will set up a project and create an entry point for application and create a command to start so whenever you download a new node project if you are cloning one from GitHub or whatever it may be you will most likely want to check the package.json check the scripts see what the command is to run it most likely it's start or something very similar and that is how you're going to run the project you can create multiple variations so you could have a start and then you could have a Dev start if you wanted to do things a little bit different in a development environment but for now we're just going to need one in the next video we're going to talk about basic dependencies this will allow us to bring in software that other people I've written into our project to save us time and to be able to do new things so stay tuned for the next video I'm looking forward to it peace out welcome everybody to your node.js episode for this video we're going to talk about dependencies and node package manager basically I'm going to show you how to search for and install packages packages being software that other people have written that we can pull into our projects so here we are back in our project the easiest way to start with packages is to go through an example so let's go ahead and start with a clean slate here we'll say npm which is node package manager install and then whatever the package name is called let's go with uuid this is a pretty simple package that will allow us to Generate random identifiers and it says added one package it found zero vulnerabilities when you go back to your package.json in this case asks if we want to reload it and we will reload that and now it says dependencies uuid is 9.0.0 and what this means is this is the version of the dependency that we want so if they end up releasing a new version we can specify exactly what we want as software is continually developing and updating there's not just going to be one version of a software there will actually be multiple but there's this important character here this carrot symbol a capital six I guess you could say and what this says is that we are okay with any version as long as it starts with a nine so any minor version change is totally okay so this is not a specific version but rather a version range anything nine or greater without going to ten so what that means is we're also going to have this other file which is packagelock.json and this is going to say the exact version so here you can see again our packages with what is acceptable but the specific version we are using is 9.0.0 so let's go through that one more time package.json is going to say what range of possible versions are okay to be used and then package Dash lock.json is what version is actually being used this package lock file can be generated so what that means is I can go in here and I can delete that file and when you do this you can regenerate what versions you have so if we only had the package.json file we could say hey let's go ahead and get all the exact versions by saying npm install and that's going to go through the package.json and grab any of the dependencies and you may need to do a refresh for that new package lock to show up and you can see again it generated the same version in this case you'll also notice we now have this node modules folder this is where the source code for these packages are actually stored so this will be generated as well so let's go through an example let's go ahead and delete the node modules and you may or may not have the package lock.json let's go ahead and just delete it since it can be generated anyways and let's say this is what you've been given from a friend you have some project and this is all they give you so we just have the package.json and then we have the source code this might be what a friend gives you if you're working on a project together or this might be from GitHub or some other website if you download a project so the process to get everything not only the exact versions but also the source code would just be to issue npm install as we've shown earlier but you can also just do npmi this is going to then you saw that bar for a second actually re-download that code and now we have the actual source code downloaded in our project because the source code can be retrieved we don't have to include this in any Version Control System like git we'll talk about that in an upcoming episode here shortly so the packaged lock.json if you're going to share this project with other people such as inside a version control or just sending it directly to somebody it's recommended that you do include the package lock file that way if I'm working on the project and you are working on the project we have the exact same versions of those dependencies I don't have 9.0.0 and you have 9.0.1 there might have been some change in that minor change that could make our code a little bit different and it might not work on your machine or my machine even though we have the same code because of that difference so whenever you check this code into Version Control it's recommended to include the package.json and the packagelog.json and we're actually going to go through the process of version control setup in probably the next video so let's now talk about where the source code for these packages come from you know how do we just type in some command in the terminal and then it just shows up in our project that doesn't make a lot of sense well all of the source code for these packages is stored in this package repository npmjs.com so we can go in here and search for whatever package we're looking at such as uuid and this is a description of that package we just installed and you can see the code for this as well and versions so here are the different versions that have been created Total weekly downloads kind of insane and you can also go to that repository in GitHub so here is that repo if you want all the details for the code or if you want to clone this and modify however you might want to do it that is how you would do that this is also where you can search things so for example if you wanted to work with time you could just type in time it'll show some pop-ups you can just hit search to and see some more information sorting by popularity or whatever it may be one we're going to be using is Express this is going to allow us to build our websites and if you go in here you can go into 31 dependencies and here are some of the other packages that this package needs to work so if we went over here and set npm install Express it's going to actually install quite a bit of packages behind the scenes so you can see it going through here and it says added 57 packages now our dependencies have updated so it just has express it doesn't list out all those other dependencies but inside of our node modules you can see the source code for a ton of different packages that this Express package depends on so that is an introduction to getting packages and searching for packages now let's talk about how to actually use them real quick and overall it's pretty simple we can go into our source code and we're going to require that code so we will say const and we'll just say uuid and we'll say require and inside of parentheses we will put the name of the package uuid now there are things that we can access on uuid however this is an object and we can actually destructure this object and grab something inside of it using curly braces it's a little complicated if you're not familiar with JavaScript but don't worry too much about it right now we can grab the V4 property giving it uuidv4 name so now you can execute code like this console log passing in uuid V4 and this is a function call so this will give us the unique identifier we can execute our code with npm Run start and we can see the unique identifier right there all of the different packages we use are going to be used in a similar way you might not have the object destructuring here so it might just be a name but overall it's going to be pretty similar now I wanted to show you another way you might see things but pretty much what we have so far is going to get you pretty far so I want to worry too much about it but if you're familiar with react you might have seen instead of require you see import and that syntax is going to look like this import and then inside of curly braces we will take V4 as uuid V4 from uuid this is the other syntax you might see however if we try to run this code you're going to get an error and it says cannot use import statement outside a module well there's two real different types of importing there is the common JS way which is what we were just using and then the es6 way which is what we're doing here and this is not supported by default so what you need to do is inside a package.json you can add a property in here which is type and the value for this would be module this should fix the problem but I still believe the preferred way that we're going to be using is to use the common JS import but let's just run this and see if we can get it to work and you can see it works that way just the same so that is why if you are coming from react you might see this which is different than the way you'll often see it with node.js so let's go ahead and restore this back to what it was right there and we will remove type module from the package Json all right and then finally let's just run it to make sure everything is working for the next video because we're going to be checking this code into Source control all right seems to be good one final note is if you're following along with this series and you want to be sure to be using exactly the same code as me you can be sure that your dependencies are set to exactly the same so you could go in here and set a specific number to match the package lock Json and I'll have this up in GitHub probably by the end of the next video that way you don't have any code changes and everything should work exactly the same way you could also clone this repo from GitHub as well alright so that's the intro to packages I guess this took a little bit longer than I was expecting had a lot to cover that hopefully was helpful stay tuned for the next video and we'll get this up in Version Control peace out welcome everybody to episode 5 in your node.js tutorial Series this episode we're going to talk about how to set up git and GitHub for our project this will allow us to check in our code to Version Control and have that safe as well as track changes over time this is basically going to be the way all software projects are built when you move Beyond just your single person so if you're working in a team you're going to be using most likely git so here is an example GitHub page this is mine and I have all of my repos on here so I can you know keep track of all my code but GitHub is different than git so GitHub is a company owned by Microsoft and this is where you can upload your git repositories git on the other hand is the actual software so you can find that at get Dash scm.com and download for Mac or for Windows so you can check if you have git by saying git in the terminal hopefully you get some usage response I'm in a virtual environment so it's running a bit slow but no big deal if you get an error like this that just means you need to go install git so I will download that and go for the 64-bit install we will say yes and now go through pretty much the default install settings nothing too crazy I'm not going to go through this step by step I'm going to change the default Branch name to main that's recommended and I will go with this setting as well for the where to use the git command so hit next yup and I just went through the defaults on the all the other stuff and I'll let this install when you install git it's going to install Min GW which is basically a way that you can have a Linux like terminal on Windows which I generally prefer to use if you're on Mac then it's not really going to be much different you can just use the normal terminal and the commands you're familiar with already and that can be accessed with Git bash so I'll launch that this is what it's going to look like and I'm going to replace our Powershell with Git bash you can zoom in with control plus minus and we're going to change directory into this location of our project which is in documents and then into uh customers and you can clear the screen with clear and now you should be able to say git init initialize an empty git repository in this location now you can have the option to show hidden files or folders so when I enable that you can see there's a DOT get this refers to our repository and does all the file tracking so don't touch this you don't need to do anything with it it's just good to know that it exists the First Command you should learn is git status and it'll tell you what branch you're on and the different files that are showing up here so you can add files with Git add but before we do that I don't want to add everything which you would normally do with a DOT I actually want to ignore some files specifically node modules we don't need to check that into Source control so what we can do is we can create a file called dot git ignore and this is a file that is going to use to figure out what files to not put into Version Control Source control Version Control all the same thing I'm using words interchangeably here so you could say node underscore modules save that and now when we say get status that node modules is no longer there so there's a lot of different files you might want to ignore there's actually some good default files that you can just start with out on the internet so I'll usually just search topdol and then say what language I'm using so top to node.js get ignore and you can find that right here so we can copy this this is just going to put some of the most common file formats and stuff that we don't want to put inside of Version Control and I will just replace this here and now we have a bunch of stuff and most likely we've covered everything that we're going to need to ignore cool so we'll save this and then what I'm going to do is I'm going to add everything so git add dot that'll add the current directory and now when we say get status you can see they're green and it shows that there's some new files being watched and ready to be committed so when we say git add dot it's saying hey we're about ready to make our first commit but we haven't actually committed to it yet to actually finish we'll say git commit Dash M with some quotes and some message usually I'll just say initial commit and it tells us to run these commands first here so we will need to set our user and email and username so I'm going to go ahead and take this here paste that down here and then I'll just go back and change these values stupid activate Windows is in the way all right so I set the email now I need to go grab the username as well so I will copy this and change this to Caleb Curry all right so we set up that configuration and now we should be able to commit so we can use the up arrows to go back to our previous command gate commit Dash M initial commit and it makes that commit now when we say git log we should see that commit in our commit history and it says initial commit so far so good now when we say get status it'll say that there's no changes but if we went in and changed any of these files let's say inside app.js we changed something here like let's just remove this line for example and save now when we say get status and notice there's a change and we can track those changes over time so if you introduce a bug you can backtrack to the different commits to figure out where that bug was introduced now from GitHub you're going to want to create an account or sign in and from here go ahead and create a new Repository give us some name node.js and select an owner if you are part of multiple organizations we'll go with public ignore all this stuff we're not going to initialize the repository because we did that on our local machine so we'll create Repository and we will go with the second option push an existing repository from the command line so we'll copy this over and we will paste that here and hit enter now this is actually going to pop up a sign in for me where I'm going to have to sign in and I just got that done so we should now be able to issue these commands and you can see it is working on it cool so once that's done we should be able to visit our repo do a refresh and you can see our code is now there and that means you could go to this URL and compare your code to mine if for some reason someone's not working or you could just clone this repo if you are familiar with doing that so you could take this and from any terminal window you can say git clone paste that URL and now you can access that code on a different machine you would just say CD into node.js and then you're going to need to get all the packages so you would say npm install and that is the process for cloning and installing the packages npm Run start and there we go there is our unique identifier so far so good you got your project you got it up in GitHub and you can pull it down to another computer so now you have a backup for all your code and you can now change code more aggressively without worrying about breaking it and not being able to figure out where you went wrong because you could always go back to where you had it there's a bunch of different gig commands out there can get a little complicated but it's something you'll become more familiar with over time and fortunately it's used for pretty much all software projects so regardless of what language you're using those are some valuable skills to have thank you for watching in the next video we're going to get started with Express peace out what's going on everybody Welcome to episode 6 in your node.js series it's been going pretty slow so far but we're finally to the point where we're going to install Express this is the most common package used for creating back-end applications so similar to what we did in an earlier video where we created a little web server and we responded to a web request Express is going to do that same thing but add a lot of capabilities and give us something that can allow us to build a more complex application so most of the time when you're building back-end services or apis you're going to be using Express there may be other options out there but Express is what I'm familiar with so let's get started we will clear out what we have and you will want to make sure you say npm install Express we did this actually in an earlier video npm wasn't working on the initial load of git for some reason so I just opened a new window and now I can say npm install Express so if you're following along with a series and you just gotta get bash then you might need to just refresh by closing out of it and opening a new window which actually I'm super dumb because when you open a new window you will need to change directory back to whatever your project directory is so we will go into documents and then into customers and now we should already have npm install Express so it should be pretty quick all right there we go so over in our package.json you can see we're going to say yes reload and don't show it again so this is our Express version and now we can head over to app.js and create a simple example I'm going to unpin this so it kind of slides over to the side there we'll say const Express require Express const app is Express so we require Express and then we create an instance of it and assign it to app now we're going to use a port later on I'm going to assign this to a const here just so we can reference it as Port I'm actually going to use all caps here and then what we'll do is we'll say app.listen and this is going to take the port and then a function to show up in the terminal when the application has been launched so we can say console log and in here I will just say something like app listening on Port and then we'll just say Port so let's try this out npm Run start app listening on Port 3000. now if we go to logos 3000 it says cannot get slash and what this means is although the server seems to be working we're not actually receiving any information and that's because we need to create an endpoint so what happens when the user visits that URL so we'll say app.get and this is going to take two arguments the first being the path if you wanted to just be the home page you're just going to use a forward slash and the second thing being a function so we'll just pass in an arrow function to find this inline so request and response very similar to what we did in episode one or two yeah I think it was two two or three I don't know earlier on in our life and we'll say res dot send hello world now we need to restart our server so close out of it make sure you saved app.js and then we'll say npm Run start app listening on Port 3000 so let's head over to the browser and do a quick refresh and now it says hello world awesome so you have a working application built in Express Now the default method for retrieving data from the browser is called get so what you can do is you can go to inspect you can do this in Chrome Firefox Edge it doesn't really matter they're all going to be pretty similar and you can go to network and when you refresh the page it's going to keep track of all of the network traffic here is our request and it says request method get however there are other methods so if you wanted to access the same page but basically change the way in which you retrieved it you could change the request method so let me show you an example of that real quick if we go back to our application we can make a new Option down here with saying it app.post which is another method that you often run into and this will be at the same path we will create an arrow function and then we will just say something else so res dot send and we'll just say this is a post request oftentimes a post is going to be used to add data where get is going to be used to retrieve data the question is how can we actually make a request to this function instead of this one as mentioned by default the browser is going to use get so we're going to need a new technique one way is to create an HTML form however I don't really want to create an HTML form because I really want to be working with data and Json to create apis so we're going to get into more of what that means and what that looks like but we'll start with the next video where we are going to install a tool to allow us to make post requests to our endpoints so stay tuned and be sure to subscribe welcome everybody in this episode we're going to talk about making requests to our web server using different HTTP methods the easiest way to do this to test your software is to use a tool such as Postman which is a fabulous tool and I'm going to show you guys how to get that installed and use it eventually you will most likely have a front-end application such as a react application that will make post requests or whatever method to the backend server but if we're just trying to make the back end endpoints we don't necessarily want to go through that whole setup process so having a tool like this comes in very handy so to get started head over to postman.com and under product you can go to get started free and download Postman whatever operating system this should be available on Mac as well there is also a web version of Postman if you want to give that a try however I haven't actually used it too much and I'm not really sure the experience with local applications so let's go ahead and just go with the download version for this series so we'll open this and go through the installation process here's some more information on the web client so you can check that out if you're going that route once Postman launches you have the option to skip the account process and just go straight to the app now if you want to put this in dark mode you can head over to settings and then under themes choose dark and to me that's a lot easier to look at now we are within a scratch Pad which basically allows us to test things and it's nothing serious but if you want to basically build a collection of multiple API calls to test out your backend you can organize those within a collection and easily call each one of those to make sure it's working correctly for us we'll just stick with this here so we're not going to worry about the collection right now so let's go ahead and create a request and we can drag this over to hide all of that information so let's go ahead and put the URL here HTTP colon slash localhost colon 3000 go ahead and hit send and we get a response hello world so if we take a look back at our code we are hitting this response if we want to hit this one first we have to make sure we are running the most up-to-date server so close out of that npm run start now I do want to show you how to make it automatically restart the server here in just a second but first let's go ahead and test this with a post request so we'll go to this drop down choose post you can see some of the other options there as well hit send and now our response is this is a poster Quest so we were able to successfully get this response here now I want to talk about how we can automatically restart the server Whenever there is a code change that way we don't have to close the server and then restart it to do this we're going to say npm install nodemon which is a tool that will basically watch to see if any saves have been made and cause the server to be refreshed now you should be able to use nodemon either by saying node Mon and then whatever file such as Source app.js if this does not work then you can also say npx node Mon and then the file and you can see that this actually started the application so that is working so this can be brought over to our package.json so changing the start to say npx node Mon and then Source slash app.js so we'll save this and you can see well for one it restarted the server but let's go ahead and just close out of the running server and we will now say npm Run start and the command now is npx node mon Source slash app.js and that works so anytime we change our files such as an app.js if we added an exclamation mark and saved this it'll restart the server and we'll automatically see those changes another important thing to know is that if you have a package.json file for your app you could omit the main script entirely and nodemon will read the package Json for the main property and use that value as the app so in our example the source app.js is the value for the main property so in theory we should be able to remove this here and now when we say npm Run start you can see the shortened command and then this server has started so it seems to be working that's your brief introduction to postman and nodemon two useful tools that we're going to be using throughout this series stay tuned for the next episode in this series peace out what's going on everybody this episode we are going to learn the basic Json structure as well as understanding objects inside of JavaScript so Json and objects in JavaScript are very similar Json actually means a JavaScript object notation there's just some minor differences and we're going to talk about what you need to know in this episode so let's go ahead and talk about Json real quick now you may hear this pronounced Json or Json either one no big deal but it's basically a way to describe data it's in agreed upon format for data and it'll allow us to easily communicate between applications through our API so you can think of the API as the means in which we communicate between applications and then Json is kind of like the chosen language to communicate between applications if you're speaking Json and I'm reading Json it's very easy to communicate so I'm using this website Json lint which is one of my favorite sites for quickly validating Json make sure you got it right so in here you can go and create an object with curly braces and it's going to be key value pairs inside of quotes for example name and then a colon and then some value such as Caleb Curry and if you want to have multiple attributes in here you will want to have a comma after the first one and any of the other ones before your final one so we'll go ahead and give us just some example data such as the industry we are in and let's say we are in the music industry now we can check to see if this is correct Json hitting this button validate Json and it says valid Json so far so good if we messed it up such as forgetting a comma we're not going to get the same result and it's going to show us where that error is I'm kind of zoomed in so it's hard to see everything but that will help us to correct our Json and find any errors that we may have now another important thing is this needs to be double quotes So if we use single quotes it's not going to work either so let's go ahead and replace those back with double quotes if we want to have nested data we can do that as well for example we could have a favorite colors and this is going to look similar to these others but instead of just having a value it's going to use square brackets and inside of the square brackets we can have multiple values so these values could be objects themselves or they could just be strings or even numbers so let's go ahead and make an example with some strings we'll say red blue and green and let's go ahead and go through another example where we might have favorite numbers in this situation we're also going to make this an array however we're not going to use quotes so we could just say five three and seven let's hit value hey Json make sure everything's good valid Json cool now let's go ahead and create one more example uh just to show some nested objects so we'll say favorite people and this will be an array and inside of here we can have multiple objects so curly braces to Define an object and we can Define whatever attributes we want in here such as their name and we'll just say Mom and then relationship maybe parent and then if we want to have another object in here we can put a comma after that object and go in here and say name dad and this will be relationship parent as well so that's just an example of nested objects we hit validate Json and it's still valid Json so we can do something pretty similar inside a JavaScript and this is very similar to a JavaScript object however when we're defining an object in code we do not need quotes and generally I'm going to recommend that you don't put spaces in your property names so instead of having spaces you could say something like favorite numbers using camel case favorite colors and favorite people so you could take this entire thing if you wanted and bring that over to your code and what we'll do is we'll just say const Json and assign it this value and end it with a semicolon after the curly brace now if we scroll down inside of any of these we could actually send that data to the user so instead of saying hello world here we could say for example have an object and we'll say data and the value for that is just going to be the Json data that we created up here so let me just make sure I got that named right yep looks good and that should do it so we will save now when you get the data we should see that data right here and you can see it's already formatted nice for us you could also select it as raw if you don't want the formatting there now you could in theory access just one attribute on this object so for example we could say dot favorite people saving this and giving it a run will now just get that data that we asked for this is one of the reasons I personally like to not have any spaces in the attributes whenever possible let's say for example we did have a space in this attribute well then the way we would have to access this is now using square brackets and then quotes like so and now we can have a space in here and let me just say data with space just so we can see that change here we'll hit send and you can see it works the same way but it's not as friendly in the JavaScript syntax so if you can keep everything the same it's going to be a lot easier so if instead we just didn't use quotes at all here and did not have a space we should be able to just use the dot operator like so removing that space as well and we'll put this back to just data all right cool so that works so you can see we don't actually need quotes in the properties for the objects in JavaScript at all so we could in theory go up here and remove all of these quotes and everything should work exactly the same way but instead of going through in here and updating everything what I want to do is actually just want to go through an example of creating a list of people so let's go ahead and kind of start fresh here so we'll say const people and I'm going to remove this and we'll just start with an empty object and inside of this object actually I take that back instead of an object let's go ahead and Define this as an array since there's going to be multiple people here and then we could just have a few objects in here so it'll look something like this I'm just making the general structure we could have three people and then inside of each person we can give it multiple attributes we'll just go with a name and an industry as an example let's say this is for a list of customers so the first one can be Caleb industry was in the music industry that's the first customer let's go in and Define the second customer here name is John and their industry is let's say networking and then lastly we'll have one down here let's say this person's name is Sal and her industry could be I don't know sports medicine whatever and then down here where we have data we could change this to be more descriptive such as customers we also want to update this value here to be correct which will be customers now let's go ahead and try this out all right there we go we got all of our customers one last thing is often you will have this data accessed and endpoint such as slash API slash customers where basically we say hey we're using an API and this is the resource we're trying to grab but if we send this now it's not going to work what we could do is we could actually customize what URL the person needs to access in order for it to work here so instead of Slash here we could have slash API slash customers and if you wanted you could still have just a general slash for the home page so we'll say app.get and inside of here we will just have a very basic example just to say welcome so I will Define a function here to find the request in the response and then we'll say response dot send and we'll just send a string saying welcome so Now API customers should work and the home page should work as well so we try that that works and then if we just visited the localhost 3000 without anything we get welcome cool so we created some mock data this is a great way to just become more familiar with data and sending and receiving data but it's obviously not going to be dynamic or update in any way it's just hard coded in the software not something you're going to do very often except for when you're building out the application as you can tell we kind of isolate different pieces and get each section working so when we have mock data we can be sure our API endpoints are working and there's not some problem connecting to the database then we can add the database later and make sure we can replace our mock data with real data instead of doing everything all at once when you're learning sometimes it's easier to split it up into different categories like that if you're more experienced you might be able to just go in here and do multiple things at once but this being a beginner course in US building up from scratch it makes a little bit of sense to use mock data thank you for watching this video stay tuned for the next episode and I will see you then peace out what's going on everybody in this episode we're going to talk about how we can get the values sent in the body of an API request this is often used to provide some additional information for any request usually used in a post request or some of these other methods we have the ability to provide a body and when we do this there's different types that we can use I'm going to go with raw and then select Json so we have the ability to provide Json data to a request so let's talk about what this might look like let me zoom in a little bit so we can see a little better we will provide an object and some values let's go ahead and say we have let's say it's a customer and they have a name new customer and then we'll have some industry for this customer and we'll just say technology or something so we want to be able to send this to our back end and get these values on the back end this will allow us to store that information in the database or do something with it so first off we need to Define where we want to send this data we could just have this at the forward slash home page with a post but instead I think I'm going to have it for the API customers so what I'll do is I will create a new endpoint here and say app.post and inside of here the path is going to be slash API slash customers and then we'll provide a function here and the function will have the request and the response as the parameter and inside of here what I want to do is I want to read the body the way you'll often see this is with the request dot body and this will have that value so what we could do for example is say console log request.body and when we do this we should see this not in the browser console but the server console over here so let's give this a save the server restarts we will also likely want to send some response so we could send the same exact thing if we wanted so basically just Echo whatever they're saying so we'll just say request dot body okay so let's save this the server restarts and now from Postman make sure we're at localhost 3000 slash API slash customers confirm we are doing a post request and hit send when we do this you can see nothing shows up in the body response taking a look at the console you will see the value undefined so there's one more thing you need to do in order for this to work probably towards the top we'll scroll up where we have Express we're going to do two more things with this app constant here so we'll say app dot use and we'll say Express dot Json and then the next line will be app.use and this line will have Express dot URL encoded and this will be a function call a method called so have parentheses and it will take an argument which is an object containing the extended property set to true so that should do it so save this and now we will need to restart our server so we'll say npm Run start we got our server running and now let's head over to postman from here we will hit send and now you can see that value in the body additionally this should show up in the console you can see that object displayed here so what exactly are these lines doing I don't know all the details but we're basically adding middleware which will be able to parse that data passed in through the body so this will basically affect all of the requests coming in so if for any reason you're building applications in the future you're getting an undefined body it very well could be this problem so make sure you put that option in your head and come back to this video if that ever happens so we've been working on this code but we're not really using any real data even up here we have this mock data here and the data that we're passing to this body this API endpoint through the body is just being logged and then sent back to the client nothing too useful so what I want to talk about now is how we can actually persist this data in a database that will allow this application to have memory and we'll be able to add customers view customers delete customers update customers whatever we want to build in this application so we're going to get started in the next video with setting up mongodb I'm super stoked I hope you are as well I'll see in the next one and peace out what's going on everybody this video we're finally going to start working with a database we're going to set that up in this video we're going to be using mongodb is there any reason in particular I'm going with mongodb not really I think you could use multiple databases but it's very common for mongodb to be used with node it's very simple to get started and uh I like mongodb so yeah now we're going to be using mongodb in the cloud which means we don't have to download anything if you want to download a database you can do that as well I have grown to prefer Cloud providers for various reasons I can work on the project across multiple computers with less setup I am less responsible than most of these Cloud providers so I trust them to keep my database more safer than if I did it myself let's just be honest Cloud providers are either cheap or very free to get start cheaper very free really Caleb they are either free or very cheap and it can also give you basically an exact copy of the setup for production so I'm going to be using a cloud database for development and a cloud database for production either the same database or a separate database you could do either one so to get started with mongodb we're going to use mongodb Atlas so go to mongodb atlas website sign up and we'll get started so here we are mongodb.com Atlas and then you can select try free or if you have an account you can sign in now when you get into the website it's going to look something like this and I already have this customer's cluster here so what we can do is we can just start from complete scratch we're going to delete this now I can't remember if this was for testing or if this was my production database but uh no big deal so we'll just go ahead and delete this oh you know what I think that was from my company oh shoot so for you it'll probably look like this and then what you can do is go with the free option and hit create I'm going to leave all these settings as the default you can look through them if you wish and we'll create a cluster now to authenticate your connection you can set a username and password I already have an account here so I'm going to go with that user and then for this where would you like to connect from you're going to want to use my local environment and for this option I added this 0.0 option which will allow you to connect from anywhere this isn't really recommended from a security point of view really you should only be adding the IP addresses for your specific networks that you're connecting from so if you want to do that you can add your current IP address for development and testing I'll often do this but just let you know it's not really the recommended way to go so I'm going to finish this and go to the dashboard and let this start up all right so from here you have your database you can click this to get more information you can go to collections to see the data inside of your database and you can review the security connections over here on the left so database access you have your users so if you need to edit or create a new user we're going to need that for our connection string as well as the IP addresses so back from this page you can hit the connect button and it'll give you some options on how to connect to this you can select hey I'll connect from my application and this will help you create a connection string and we will be doing this in the upcoming episode where I'll be telling you how to connect to mongodb from your node.js application I want to talk briefly a little bit more about mongodb this is a document oriented database a nosql database and what that means is it's very similar to Json data where you have key value pairs as opposed to tables consisting of columns and rows that would be a structured database like MySQL SQL Server Oracle postgres any of those databases are going to be very structured an unstructured database can make it pretty easy to develop your application make changes over time be a little bit more Dynamic but it can also be sloppy if you're not careful so I would still think about what is the general structure of my data and you're actually going to Define this in your code because we're going to basically have some software Mongoose which is going to connect us from mongodb to our node.js application and we're going to describe what our data structure should be so that when we send data to our API it knows what to do with that information and how to store that in the database we will get started in the next video connecting to our database from node and then we'll learn how to start building our schemas and putting data in the database thank you for watching stay tuned I'll see you in the next video peace out welcome to your next node video in this video we're going to talk about how we can connect to mongodb from our node application so a quick prerequisite which you can check out the previous video if you want to know how to set up mongodb in the cloud you will want to have a database going and you can see there's a connection string here when you try to connect to this cluster so from mongodb Atlas you have your cluster you hit connect and then connect your application we're using node.js there's also an example for include full driver code example which you can go through this if you wish we're going to do a little bit different but it's going to be fairly similar but we'll build that from scratch so we are going to end up using this connection string though so the very first thing what we're going to do is we're actually going to close out of our server because we're going to install something npm install mongoose and this is how we're going to connect to mongodb so this is an object modeler for node.js basically it's a way that we can go from mongodb objects to objects enter code so we describe some model and then we can create a new instance of that and then save that to our database that is the summary so once that is installed we should be able to include it in our code so let's go ahead and scroll up to the top and we are going to require Mongoose by saying require and passing in Mongoose and then an additional setting is going to be Mongoose dot set and the value will be strict query setting this to false which you can do more research on if you're interested that should be the only thing required to actually get Mongoose in your code to use it we're going to Define an async function which I believe makes working with Mongoose a little bit easier so we'll just scroll down to the bottom and down here we will create a function we'll call it start for example and we'll just Define this as an async arrow function so it's going to look like this and then inside of the curly braces is where we will Define the actual function code so to connect you can use the await keyword inside of the async function and say Mongoose dot connect this is where we will pass our connection string afterwards we can actually start our application so that's going to be this same code here what we're normally doing just at the end of our file we will now put inside of our start function so once we're connected to mongodb we will then launch our application and I'm just going to indent this to make everything match correctly cool so now this function is not going to execute until we invoke it so at the end we will then invoke start now obviously this isn't enough because we haven't even put our connection string in here but you can kind of go with it and do this in steps same I say npm Run start make sure we're on the right track and obviously we're going to get an error so we need to consider two things first what should the connection string look like here and what happens if there is an error which is going to require us to have a try catch section which I'll show you how to do that in just a moment so let's first try to fix this first error by providing a connection string so over in mongodb Atlas we will go ahead and connect from our application copy this and paste that here and we're going to talk about environment variables and such in the upcoming episodes for now I'm just going to hard code paste that here now there's a few things we need to replace specifically these username and password and the angle brackets should be removed as well so that's saying to substitute the entire value so I'll provide my username and then my super secure password which I believe is not password very secure all right there we go now it says app listening on Port 3000 so it was able to successfully connect if we had for example the incorrect password we would get an exception Throne if you're unsure where to get your username and password check out the previous video you can find that in the side panel on mongodb Atlas real quick I'll show you that you can go to database access and here are your users so you can add a new database user or use one of these existing users so let's take a moment to pause and talk about exceptions for those of you who are new an exception is when our code breaks during execution so it's running it's working so far and something has hit that the code is unable to deal with that is known as an exception it's our responsibility to code what happens when an exception is thrown and you do that with a try catch section so we try some code and then we can catch that exception and say what should happen usually that'll just log maybe tell the user something's broken sorry try again later whatever that may be or you know you could retry after a certain period of time various different things you can do so let's first fix this password so that it's correct and then we will add the try catch and make sure our code can work as is with the try catch and then we can test what happens when things don't work right so to create a try you will say try and then surround whatever you want to try in curly braces so it's going to look like that and then we'll just take everything inside and indent it so that's the structure now when you have a try you're also going to want a catch and you have parentheses and then curly braces so that's the structure inside of the parentheses you're going to Define a variable which is going to be an object containing that error so usually this will be called e or error or error so I'm just going to go with E and down here we could say console log e and there will be a property on it called message so let's save this and you can see the code seems to be working as we expected app listening on Port 3000 let's go ahead and now break it let's go ahead and change our username maybe and it just says bad off authentication failed so this is the message given back by E Dot message what we've seen before before we had this try catch it was just like a huge section of broken stuff like this here this is called the stack trace and it's basically a history of what happened at what lines to lead up to that exception so usually a nice human friendly message is better now this is on the server so this message is not going to be sent to the user on the web browser so you would need to see this in your backend logs since this is all backend code so that's all you really have to do to connect to mongodb but there is one big problem with our code that we're going to fix in the next video and that is we have this connection string hard coded in our application this is generally a really bad practice for multiple reasons usually if you're going to check this code into Version Control then this password is available just in the code for people to read it might not be open source but if you ever did open source this it's a big risk even if you're just working in a small team and it's all closed source so the public can't see the code well maybe not everybody should just have that connection string right there realistically that connection string should really only be known by the server the computer that is running the backend software that way not anybody can just access the database and Tinker with the data that's generally the best practice so instead what we can do is we could read this connection string from a file on our local environment that would not be put into Version Control and that's what we're going to be talking about in the next video so stay tuned be sure to subscribe and peace out what's going on everybody this episode we're going to be talking about environment files or environment variables these are often defined in a hidden file on your local machine so these are something you're not going to check into Version Control so you're not going to put it in git and you're not going to share this file with other people it's going to contain information that's just used for you now oftentimes the values will be very similar for other people or maybe even the same so oftentimes default values will be used in the code and then we have the ability to overwrite those values using local values if we choose to a very common example of what I just described is with the port used for the server by default it's 3000 but we have the ability to give a custom Port if we want to use 3000 for something else we could use 3001 or whatever it might be so we're going to learn how to create an environment file for our Port Choice as well as our mongodb connection string the first major change you want to make in your code instead of assigning a value to Port directly you have the ability to get this from an environment file so this will usually look like process.env.port or 3000 if that is undefined so this is a very common setup that you will see now down here where we start our server at the bottom here where it says app.listen port we say app listening on Port and then display that value so if we provide a different value we should see that in the console as well as be able to access the site from a different URL now I want to talk about before we go in and create an environment file there's an alternative way to provide values for the environment so when you run your server the way we've been running it is if you check out the package.json we have this start command which is npx node mod you may occasionally see people start the server differently where they provide a value for something so for example Port is equal to 3001 and then they'll say npx node Mon and this works in a very similar way looks like we're having an authentication failed but that's just mongodb so let me go back and actually update that username and password and you can see app listening on Port 3001. what that means is for our calls we actually need to change this port and now it'll work on 3001 and you can see it's still working this value can actually be passed through using npm Run start so for example if we issue the previous command we just issued Port 3001 and just said npm Run start this port is going to still work so you might see that as well and there you go app listening report 3001. so basically what this is doing is it's getting that Value First and realizes there is no need for the default 3000 you could of course do the same idea for the connection string so you could say const connection or con or whatever and then get this from process.env y.com but I don't think it'd be very convenient to have to pass that in the terminal every single time you run the application so we're going to talk about a different way to do this so we can just do it one time and that is with an environment file so if you take a look at your project it will go back to the root of our project and we'll create a new file so just right click anywhere and say new file this is going to be called dot EnV so it's a hidden file and this is where the environment variables are going to be read from by default so let's go ahead and open that file and we will try to Define one here such as the port and the Syntax for this is just like we did inside of the terminal so we'll just say Port is equal to some value let's go with a different number just to be sure that this is actually being read from this file so we will save this however this is not going to work by default what that means is if we close out of our running server and we relaunch this this time just using npm Run start without passing in the port it's not just going to magically get this port from the EnV file you can see it still says Port 3000 down here we need to do one more thing so what we'll do is we will close out of this and we actually need to tell it how to get the port from the environment file so we'll say npm install and we're going to use a dependency called dot EnV and this is how we're going to read from this file all right so that package is installed now what you can do is inside of app.js you can require that package and use the config method to retrieve values so we will do that here after these other two requires so we'll say const dot and for example and we'll say require passing in dot EnV now you can say dot EnV Dot config now we'll say npm Run start and you can see it now says listening on Port 3005. so that's all you have to do to have it automatically read from the environment file now there's a few other ways you might see this set up a common setup is if you only wanted to read from the environment file if you're not in production you can basically create an if statement for that structure so let's talk about how we can do that where you do this is probably not a big deal I'm going to do it down here before we grab the port and we'll say if and then I'll just Define that structure real quick process dot EnV Dot node EnV is not equal to production so if we don't flag our npm Run start with node environment being equal to production then we will read from the dot e and v file with DOT EnV dot config and then we will remove this line up here so we don't just do it all the time so let's see if this works the way we expect let's go ahead and just restart the server just to make sure we are solid npm Run start and you can see it says app listening report 3005. if you wanted to change that and say hey this is now in production what you would do is just say node and is equal to production and then npm run start and now it says app listening on Port 3000. you'll often see the shortened two just by doing the require at the same time which you know you can be very Dynamic with this so we'll say require then dot on that this will replace the need for the dot e and V here actually so it'll just say require dot EnV dot config and now we can remove this line all together now just to be sure I'm not crazy we will issue another npm run start and see that we were able to get the app running on 3005. now I could do something very similar for the connection string so to say const connection is coming from process.env dot connection and we will use this instead of the hard-coded value down below now you could pass this through the terminal or within the environment file which is most likely what you're going to be doing so we would just cut this connection string out of here remove that and we'll also remove those quotes there and just replace it with connection now we'll take the new connection string value and place it inside of the environment so paste now you don't need quotes here so this is what it's going to look like we'll save make sure that is saved and app.js is saved so that it's actually getting the new changes and now you can confirm things are working so what we'll do is we'll just restart npm Run start and it appears to be working as it once did but now we don't have our connection string in our code now there's one more very important thing you need to do and that is add your environment file to your git ignore so you don't check it into Version Control and expose those values to the internet most likely if you've used a getting or template like I did that'll already be in here so if I search dot EnV you can see that here so what that means is if I say get status you're not going to see anything about a DOT EnV file it should not show up in your repo at all that means you will need some setup instructions you will need to make sure you know to set these up when you clone this repo in the future so you might need to instead of having a EnV file have a DOT EnV example file with some fake values here that is then something you could check into Version Control and people could see so they know what they need to set up they could then just rename it to dot EnV change the values and they're good to go that's all I got in this video stay tuned for the next video where we're actually going to start working with mongodb schemas inside of our code so stay tuned and be sure to subscribe hey everybody in this episode we're going to be talking about schemas and models for Mongoose to connect to our mongodb database to begin I wanted to explain that you can do things inside of the single app.js file but as your code continues to grow in size it's going to get a little unwieldy so what I would recommend is actually creating a new folder for all of your models the models are going to describe your different data structures that you're going to want to store in your database So within our project we're just going to add a new folder and I'm going to call this models and inside of here we can store all of our different model files so they're nice and easy to find to begin let's go ahead and add a new file and this is going to be called customer.js now we can kinda isolate the Mongoose functionality for this model so it's not polluting our main app.js file so the very first thing is we're going to use a mongoose so we'll say Mongoose and require Mongoose now you might be wondering if we're defining this in a separate Javascript file how can we kind of combine all of these and run them at the same time well all we have to do is over an app.js we just require our new customer file that we created so for example after these other requirements we can say const and we'll just call this customer with a Capital C here which is just a convention to basically say hey this is how we are going to instantiate customers if you have a lowercase C it tends to describe an individual customer so I like to use an uppercase customer there you may also see this like customer model but I'm just going to keep it customer with capital c and then require and then inside of quotes we can actually just use a path so model slash customers so this dot slash means the same directory and then the models directory and then the customers file so now this code is available inside of app.js so the code is still empty though so we need to go back to the customer.js file and start defining our model the way you define a model is actually by creating a schema so the schema actually describes the structure and this is how you would define it customer schema is a new Mongoose dot schema and I'm actually going to Define this with const now inside of the parentheses you will create an object and give it various properties the properties are going to basically be the columns you can think of them as the different attributes that you want for a customer this is just describing the customer structure so we'll have a name which will be of type string and we will have an industry which will be of type string we're just going to keep it very basic for this example now to actually make this a model which is basically an association from this structure here to an actual collection in mongodb you will say Mongoose dot model and pass in first the collection name which is going to be customer and then the schema that we just created and this may seem strange at first but after you do this a few times it'll just become a habit the only other thing is on the left we're going to say module.exports this describes what things we're going to export from this file for when we import them or require them in other files such as app.js great so so far so good now to create one of these customers will basically Make an instance of our schema so where do you want to do this let's go ahead and just go down here to where we have our API endpoints and we'll just use this home page as an example let's just create a customer and send it to the user when they access that that uh endpoint so we'll say const customer is a new customer with a Capital C here so note the difference this is a capital and then the actual constant or the variable that we create is a lowercase C new customer and now we provide values for those different properties so inside of the curly braces we'll say name Caleb and let's go with industry is marketing industry whatever that is now we can send this back to the user as an example object so we'll just pass customer here save everything and make sure the server is running and PM Run start all right we're getting an error cannot find module models slash customers and that's just because I made it plural when it should be singular so customer however there's one more thing I did not consider at the beginning of this video and that is where I placed the models directory currently these folders are within the same directory so if you take a look at our folder structure we have source and models all within our root directory for our project so what I would rather do is actually move our models directory into Source models and now this should work because inside of source we have app.js in the models directory so we're saying hey within the same directory go into the models folder and then grab the customer file and we want to make sure we don't have a space there so that should do the trick and you can see it says app listing on Port 3005. so that was a pretty dumb mistake on my part I probably should have just put that models directory inside of the source directory to begin with I think that's probably the better structure just to have all your Source inside of a single folder however instead of redoing this video I think that would be a fairly common mistake so I think it is better for me to show that so you guys can learn from that mistake plus I don't really want to redo the video so yeah uh let's get back to it let's go ahead and make an API request let's go ahead and change the port now to 3005 because that's what we're using and we'll just get it from the home page and make a get request hit send and it sends us that example object back you can see it has this ID which is automatically added by Mongoose and that's what's going to be put inside of the database once it's saved in the next video what we're going to do is talk about how we can save this object to the database and then read it from the database to display it to the user to give you a little sneak peek of this where we Define that object we have the ability to say customer dot save and when we execute this code this is going to be saved to the database what that means is if we go back to mongodb and click browse collections you're going to see this new test collection and it just broke but you get the idea so let's browse collections and we have this test collection with that data but in the next video we're going to talk about how we can change this from test to whatever we want it to be and how we can read this data from the database and display it as a response to the API request instead of just getting the JavaScript data that we hard coded I want to actually retrieve it from the database and display it here stay tuned for the next video I'm really excited it's where things are finally starting to come together we're working with a database we're reading data saving data and we're building an interactive application a lot of these things might seem like oh like let's get to the point but it's very important to learn these different Lego pieces so you can start piecing them together and building more complex applications so don't get bored stick with it you're almost there you just got like a billion more videos to go so stay tuned I'll see you in the next one peace out what's going on everybody this episode we're going to talk about how to read data from mongodb using Mongoose to use inside of our API so a lot of words let's just go through an example I recommend checking out the previous video it may be a couple of the other previous videos to get some basic experience with setting up Mongoose connecting to mongodb and how to create a schema we'll do a quick quick review in this video but we're not going to go in a lot of detail we did this manually by defining the customer and then saying customer dot save well I'm actually going to remove that line right away because what's going to happen is every time we run this code it's going to save a new customer when you create a customer object like this it's only temporary it doesn't get stored in the database until you hit save one other thing is that it saved it to this test database if you want to change the name of this database the default database you can do that in your connection string so if you head over to your dot EnV and you you scroll over in your connection string you're going to likely see this mongodb.net and then this retry writes well after the.net but before the question mark you can say what you want the database name to be here I'm going to put customers and now what's going to happen is I'm going to actually rerun that command we just had which was customer.save so we'll say customer dot save I'm going to run this code once so make sure everything is saved and say npm Run start it's going to go through the code and eventually hit the customer.save and put it in the database so the app is listening on Port 3005. what that means is I should be able to refresh over in mongodb and you can see now we have a test we also have customers and inside of this customer's database we have a customer's collection which has our new object this is all based on the schema we defined in the previous video which is currently not open to this customer.js this file defines that structure with the name in the industry and then this is where you say what collection you want it to go in let's say we wanted to change this from customers to something like clients when we save that's going to restart the server reissue the save command and now we can actually just do a refresh over here with this refresh button instead of refreshing the whole page and now we have this clients collection notice it's plural so in this example I used clients and it created a clients collection the previous example I just had this be customer and when we do this it's going to go inside of the customer's collection plural so you can see I've issued this a few times and now I have some data adding up so it's automatically going to pluralize and lowercase that value so that's just an important thing to know anywho I'm getting a bunch of junk data in here you can always delete these just by hitting the delete button which doesn't take too long if you only have a few values here and there we go we just have one example so now the question is how can we read this from the database and get it to display in our application we'll head over back to app.js we'll remove the customer.save and then inside of any of these endpoints we will get the customers let's go ahead and use this API customers to get all of the customers so basically we want to replace this value here instead of that mock data we want to read it from the database so to do this what we're going to do is pretty much anything with mongodb is going to be done async so we'll say async and then inside of the function we can say const result is await customer with a Capital C so referring to that schema that we created is and then dot find that's actually going to get all the data with no filter it's just going to grab everything and then what we can do is replace this here with result so let's save this and give it a try so from Postman I'm going to go to slash API customers hit send and here is the response the customer's data ignore this V thing it's something I think Mongoose uses that we don't have to actually do anything with but the ID should match what shows up in the database so this one ends in 6a9bc if we head over to the database you can see 6a9bc so it's referring to the same object as Caleb and Industry if we had more data in this for example if we created a new customer here we'll call him John and we issued customer.save once saving this it refreshes the server that code gets executed now when we retrieve the data we see two customers Additionally you can go into the database directly and insert a document so to do that you go in here and you can provide the attributes and the values for those attributes as well as the data type we'll just skip that for now since we already got some data in the database now we're going to remove the customer.save because we only want to do that one time whenever we want to just you know create a customer for testing's sake this home page this slash we're going to just change this back to some kind of Welcome message welcome and another thing you might see is instead of res dot send you might see res dot Json there's some minor differences you can research if you're interested but both of these are going to do pretty much the same thing I think in the case of sending Json data it makes sense to use res dot Json but let's just check out make sure everything looks the same and yes it does now similar to how when we connected to mongodb the first time we had this track hatch in case something went wrong we can do something very similar here so if you want to try to set up that structure as a test you could try that now Hint it uses try okay let's go ahead and do it so we'll say try and we will surround everything in these curly braces and then just indent these two lines and then catch and inside of here you can actually change what status code you send back so for example a common thing to do would say send back status 500. and then you can pass in Json data to return which is usually just going to be a human readable error so you could say error is e Dot message or you could just say something went wrong if you don't want to give any details so if that was the case you could just use a string and then for the catch you're just going to need to give it a name for the error such as e so now for any reason there's something wrong getting that data we'll get a 500 server error and send that message to the person making that request now another trick that I want to show you which is totally unrelated but kind of good to know is you can retrieve a list of the different collections so Mongoose has different things you can do so for example Mongoose Dot connection.db and then list collections and you can probably find more things you can do online but this is just one that came in handy for me at one point so we are awaiting that value but it's actually not going to hit until we actually make a request to this endpoint so hitting send now you can see a list of all the different collections in the database which includes clients and customers so that's just one thing you could do you could do other things to basically get metadata about the database if you need to do things a little bit more Dynamic but I just kind of wanted to show a little sneak peek of that nothing too serious so we're just going to delete that for now so we have the ability to read a list of customers but now I want to talk about how we can write a single customer earlier on in my example we were posting this data but now I want to take this data and actually put it in the database that's what we're going to talk about in the next video if that sounds exciting to you at all then I would appreciate a like on this video and a subscription stay tuned for the next one and peace out welcome back to your note Series this video we are going to be talking about posting data and saving it to the database this is very important if we want to add data to an application and yeah that's pretty much it so to save data we are going to be working with the post method and in this case we're going to be a slash API slash customers we already talked about how to get the request body we can console log that if we wish just to see that in the console but what we need to do is we actually need to create a new customer here to do that we can say const customer give it some name and then we'll say new customer and then eventually we will say customer dot save now there's a few more steps obviously because we're creating this new customer but we actually need to provide values for it so to do this we can create an object in here and provide values for each of the fields on a customer object coming from the request.body so the two fields we need are name this is going to come from request.body dot name since request.body is an object it makes sense to do it this way in an industry is request.body dot industry so I want to pause here and just test this out because we can actually shorten this code a little bit my bad that should be a comma not a semicolon so our app is running we hit send I forgot to have a response but that's okay because I wanted to show you something real quick you can see we get the object here listed in the console which is going to be the exact same structure as this object created here taking a look at the database you can see that new customer defined here so it did in fact save to the database but because we're matching that structure we could just instead of creating a new object with these different properties we can just pass request.body in directly and we'll save this and I'm just going to send a response because it's driving me crazy so often we will want to use 201 which is the status code for created and then we'll provide Json which can be the customer that we created so let's go ahead and say new customer two and hit send and there we go that is our customer let's try one more thing I want to say new customer three and I want to actually add a new attribute in here test and we'll just provide this a value of test so let's go ahead and hit send and you can see that value did not show up on that new customer even though that value was received on the back end the way we have our schema set up test is not a valid property so I think using the request body here directly is totally fine unless there's a situation when you are expecting more in the request body in addition to just that customer in that case you might need to do like request.body.customer or something like that but in this situation the body is directly the customer so we don't have to worry about it so that's how we can save a little bit of time I just wanted to show you both ways of creating this new customer so in this situation we're just doing it directly from the request body now I wanted to call out that this is an object with a property customer and then that contains the object itself and this is the structure that I prefer this allows you to easily in your response include other stuff if you wanted after the customer and also just for consistency sake so this is the structure I go for and I wanted to explain in our code if you're not super familiar with the JavaScript and you're still kind of learning this is a shorthand way of saying hey we want a property called customer with that customer object so this is basically the same thing as saying hey we're going to have a customer and the value of it is going to be customer so if I saved this issued this same thing so let's just increment this to customer four you see we get the same exact structure another structure you may often see is no outer object with the customer property at all and we just pass customer directly let me save this and show you what this looks like in this situation we're no longer going to have that customer property and it's just going to be those attributes either one of these will work you just have to change the way you work with this API a little bit whether or not you go into that nested customer property as mentioned I prefer to have the property which describes the data that's being shown what is it versus just having a bunch of properties with no explanation however many people would argue that that concept is redundant because you can tell what kind of resource where you're working with based on the end point but either way I'm going to go ahead and return this to how it was which is to surround this with curly braces the other thing we need to talk about is what if something goes wrong well we're going to have a try catch as usual so after we create a new customer we will try to save that customer and see if it works so we'll say try and then surround customer.save like so and then catch e for error and then inside of here we can actually we'll talk about the error in a second let's first talk about what we do if it goes right which is this right here so we'll cut this and move this inside of the try like so if things go wrong we could do something else for example give them a different status code so 201 would be created instead we could say 400 which is a bad request from the user implying that they've submitted the wrong kind of data and in here if we wanted we could have an error object having e Dot message as the value for the error property an easy way to try this out is actually to Mark certain Fields as required for the schema so if we go over to our customer.js this is our schema and we can replace this value just being string with actually an object that has the data type and whether or not it's required so let's remove this string value replace it with curly braces we will have a property which is the type and now that's where we're going to say string but we can now have a required which is either true or false so let's go ahead and say true so now if we remove everything as an example it should complain about the name not being there you can see that's not exactly what happened and this is because there's a mistake in the code that I missed initially and basically that is we have to have an await here so that way we are waiting for the customer to be saved before we try to send a response what was originally happening is we started the customer dot save and then immediately after that we gave a response and even though that customer never actually successfully saved as you can see in here on the terminal it's complaining about name being required so yeah definitely don't be a newbie like me and forget the await keyword but you know those things happen so I think it makes sense for me to show that additionally for the await keyword you will have to label the function as async okay so now we should be able to save get the app running again and now if we submit nothing in the body it'll complain saying customer validation failed name path name is required which is exactly the problem so we could actually pass a customer with nothing else other than a name and that should work as well there you go this will also help people just type things out correctly so for example if you provided the name attribute but you accidentally spelled it in a n e instead of n-a-m-e it'll complain that the name attribute is required and that would cause the user to double check the provided values realize that they have a typo so this video was quite a bit of information kind of jumping around different examples so hopefully it wasn't too hard to follow sometimes I don't like showing my mistakes and I want to re-record the content but I think you know for getting a keyword or making a small mistake here and there is pretty normal and I want to show you those problems so when you run into those same problems you're able to fix those so for those of you who are just jumping into this video from a search hopefully it wasn't too scatterbrained but for those of you who've been following along from the beginning you're probably learning a lot more and getting a lot of more useful information so let me know what you guys think thank you for the watching and I will be sure to subscribe to your viewing of the next video thank thank you so much for watching and be sure to subscribe peace out hey what's going on everybody Welcome this video we're going to be talking about parameterized URLs as well as query parameters two very similar Concepts but slightly different and we're going to talk about both of those in this video basically this is a way to pass additional information to the web server by customizing the URL that you were visiting so before we go into code and start implementing this let's just go through an example of what this looks like so you understand both parameterized URLs and query parameters which honestly you'll probably hear those used interchangeably basically a way to have some variable data some customizable data inside of the URL all right so we have our server listening on Port 3000 and we have the ability to get customers and this will basically grab all of the customers what if we wanted to grab a specific customer maybe passing in some ID to do this we could after a slash pass in that ID and most likely it'll be one of the these IDs down here from oncodb so I will copy this value and paste that here so this could allow us to get the information for just that specific user currently this does not work so this is a parameterized URL that we can Define inside of node.js but another way you might see this is instead of a slash you might see a question mark and then assigned values to different variables so this is another structure that you might see so I would say that these are query parameters this one actually works because this information is considered additional so basically this is the actual route and that ID was just a bonus however if you go the other path where you just use slashes this is actually a different path so node.js will actually see this as a different path and will accept the request differently which is why this one does not immediately work we haven't set up that end point yet so to accept some ID passed in we're going to make a get endpoint and the path is going to be slash API slash customers and then slash colon ID so the colon is to say that this is some variable and the user is going to pass in a value if they don't pass in a value then it will hit this endpoint instead of this one and then similarly it's just going to have a function here which we will Define real quick and we will make the request in the response and to get started all I'm going to do is respond by giving them back what they sent us as the ID so to do that we'll say res dot Json pass in an object and we'll say request params and assign this Rec dot params so you wouldn't have to make the in an object but we're going to add some extra here so we'll start with that so I'll save go ahead and hit send and you can see we get the request params back with the ID of this value so we're able to successfully retrieve that ID from the URL if again as mentioned we don't pass that in it's actually going to hit the other endpoint so we get all of the customers now the other way with the query parameters using the question mark and then the assignments that is going to be a different property so let's go ahead and see what those are as well so we'll put a comma and inside of here now we will have request query which is going to come from rec.query so let's try this so we'll say customers slash sum ID currently the request query is empty however if we then did a question mark and said something like ID is equal to this value and we would hit send and you can see we get that value here now so which way to do it is up to you you don't need to do both I'm just doing both here as an example to show you the different ways of doing it now an important note is if you don't pass in the ID as the path it's going to hit the other end point and the ID is not going to be displayed so if you wanted to use the query parameter like so you would need to Define that within just the plain customers path in our code so you would need to take care of that in this section of code so now that you understand the different ways of doing it I'm going to mention that my preferred way is to use a path like so instead of the query parameters however if you wanted to modify it or change some filter that is where you can often use this extra information so for example you might say age is the value 50. and then you could use that value to filter the database data more specifically to the user's request Additionally you can pass in multiple values with an and sign and say something like state is Ohio and that'll give you two values same thing with the path you can throw in another value here before the question mark and just say test and in this case it's going to give an error and like I mentioned previously when you actually use the slashes it's creating a different path so if you wanted to have nested paths like that then you would need to actually change the path in node.js so it would look something like this test it's going to give it a name real quick I don't have any good examples hit send and now you can see we get all of those values so this would typically be for nested data and not for some filtering so for example you might have customer ID and then within that customer you might have some order ID or something like that where it depends on the First Data so think of these like almost like a folder structure we're going into customers into a specific customer and then into some specific value for that customer whereas the query parameters are typically more independent you can include ones you can remove ones they don't depend on each other the next video we're going to talk about how we can take these parameterized URLs extract that ID and use that in a mongodb query to get the appropriate information to send back to the user thank you for watching peace out hey everybody in this video we're going to talk about getting an individual resource from mongodb so this is going to be a follow-up to our parameterized URLs video which we did in the last video so now we can provide an ID through the URL how do we take that value and get a specific item from mongodb with a filter and then return that to the user so here we are in our code where we have this parameterized path with the ID and we were responding with just giving that data back to the user I still want to see this so what I want to do is instead of sending this as a response I just want to console log it so I'll say console.log and then we'll have that in our terminal over here just to make sure we're getting the correct data sent from the user we can see that nice and easily so the ID in the path which is my preferred way of doing this is going to come in to request.params what that means is we could extract that value so we could say const ID and anytime I see something colored differently like that I am going to name it something else because that is reserved so we could just say customer ID for example and now you can see if we're not getting that highlighting so we know this is something custom and then just say request.params.id that is how we can get that value and I just say console log customer ID just to make sure I'm not crazy I'm a little crazy though what can I say all right let me uh update this path and then over here on the terminal you can see all that data so here is the ID and we can get that value and assign it to that variable customer ID now just a little JavaScript life hack if you are accessing some property on an object you can do what's known as destructuring and instead of saying request.params.id you can put curly braces around your variable and then just assign it whatever you are trying to get it from and then if there's a property that matches the name in that object this will work so basically it's just going to grab that ID from that object so let me just send another request real quick and you can see that worked the same exact way now obviously with the way we set it up I do now have a constant with the name ID so if ID was important to you we're kind of masking that or overriding that value so not to get too off topic but if you wanted you could rename this with customer ID so now at this point we're not really saving any typing and you could probably argue that this syntax is even potentially more confusing than what we originally had but you know YOLO we'll just give it a shot let me make a request real quick and we can see that data show up over here in the terminal all right now I've totally gotten off topic let's go ahead and make a request to mongodb so we'll say cons to customer await customer Dot find but there's actually another option and we can use called find by ID and pass in the customer ID you could also just use rec.prams.id here directly if you wished then after this let's go ahead and console log the customer just to see that data and we can send it back in a response so I'll just create an object and again with this little shortcut if you put in the object like so in curly braces it'll make a property called customer with the customer object as the value giving this a shot now we send and you can see it does retrieve that data from the database Okay cool so we can see that that is working another quick note on the destructuring that I did here it doesn't really add a lot of benefit but if we wanted to grab multiple values so you know if this was a bunch of different slashes you could do that all here at once creating multiple constants so we don't have to take up as much space so that's another benefit of using the destructuring and it's probably good to familiarize yourself with that so what we need to do is consider the case of what if something goes wrong there's an error or if the customer does not exist so let's go ahead and Surround this in a try and then what we can do is catch any errors that may show up if there's an error we'll set the status to 500 saying something's wrong with the server and will give them actually a general error message I don't want to give them too many details so we'll just say something went wrong if you wanted you could log some additional errors to yourself you know in a file or something and don't be dumb make sure you surround this in an object like so now I'm just going to clean up the formatting it's not looking too pretty that's a little bit better so this is going to take care of things if something goes wrong so for example if we deleted a character here and hit send you can see the error says something went wrong so it caught that all right so we've taken care of the scenario where you pass in an ID but this ID is not valid specifically in this case it's not enough characters from mongodb but the user may or may not know that or you know maybe there's a typo or a bug in whatever software they are writing to interact with your API so that's why we give them an error saying hey something's wrong you could give them more details if you wanted to kind of try and figure out what the problem is and tell them or you just tell them to uh check it up try again later reach support whatever whatever you want to tell them but in the case that there is a correct length ID but maybe that ID does not exist it just says customer null but it says status 200 okay now what you would typically do in this scenario is say status 404 not found so all we really need to do is just check to see if that customer data is null and if it is then change the status to 404. so here before we respond with the customer data we can say if not customer which will evaluate to true if the customer is null and then what we can do is say res dot status 404 dot Json and give them something else such as error user not found and we actually want to need quotes for that there so I'm going to remove those so now when we hit send we get error user not found status 404 not found so this is a more proper way of saying that something did not go wrong it's just that the ID was not found in the database one last code change is the fact that when we say res dot status 404 we don't have an else claw so it actually comes down to 64 and tries to send the customer and we get this error cannot set headers after they are sent to the client so to fix this what we can do is just say else and then surround this section here and I'll just go ahead and fix that indentation and now we still get the user not found which is to be expected because that comes first and we are not getting any error in the terminal from trying to set the headers again so I got on this one hopefully that's helpful in the next video we're going to be doing is we're going to be talking about updating customer data or any kind of data through the API very important very good video so stay tuned well actually I don't know if it's a good video because I'm actually made it yet but statistically speaking based off of Prior videos I've made in my life probably going to be pretty awesome so stay tuned welcome everybody this video we're going to talk about updating an individual resource in this video we're going to be talking about updating a customer so the previous episode or two we talked about how we could retrieve just an individual customer providing an ID through the URL this is really important because now that we have a way to basically identify an individual item in our database we can start adding new methods to interact with a single item so specifically the ability to update a single item and the ability to delete a single item so once we have those created the summary of possibilities will be the ability to get all customers add a customer same exact URL path just going from get to post get an individual customer by ID update a customer and delete a customer so we basically have create read update and delete but we actually have two reads one to read all the customers and one to read an individual customer this video is going to be talking about updating a customer and we're going to also learn about post versus put which are two popular methods used for updating data so when we want to create an endpoint to update a single customer it's going to look very similar to this one we created in the previous video or two where we have to provide an ID so that we know which customer to update so let's go ahead and go down here and say app.get and provide that same path so slash API slash customers slash colon ID and we will provide the Callback function real quick request response and there we go now what we're going to do is we're going to first get that customer ID I often just like to assign it to a constant so I can access it later a little bit easier so I'll say customer ID it comes from request.params.id and my bad this should not be get this should be either post or put so we're going to use put and I'm going to talk about some of the differences between these in a moment but let's go ahead and just set this to put right now and get a basic example working the function that we're going to want to use is customer dot replace one and this is going to take two things the first being an object containing what filter to find this customer by which is going to be the customer ID the second being the new customer that you want to replace it with so we'll say request dot body so we're actually going to include a body with the new updated customer data so this is interesting because we're not just updating individual attributes of a customer we're just going to take the original customer change it as we wish and provide the entire customer object back to the server that's why we are using replace one this is going to return a result so we'll say const result and then we'll send a response back to the user and I know ahead of time here that the thing that we're going to want to do is give an updated count so we'll say updated count is result.modified count but if you wanted to see all those options you could just console log it here so console log and we'll just throw in result here so let's start with this and talk about how we will use this endpoint so we'll head over to postman and we will get some data so let's go ahead and get a valid customer so I know already that this ID exists but you could just get them all and grab an ID if you need so this is the ID we want and to update this what we'll do is we will take the entire customer object and include this in the body so we can go to Raw Json and then provide that here and if we wanted to update this such as fix this spelling mistake and put their name back to how it was and you could fix the indentation here it's not required but I'm just going to do it for cleanliness now the last thing we need to talk about is the method here it's going to be put so hit send and it says updated count 1 over in the console you can see that object the result so it's going to have the modified count and that is the value that we are returning to the user the only things that we can remove from these are those two attributes we hit send this is still going to work and if we switch this to get we can get that entire customer and we can see we still have the ID on there and the underscore underscore V which I think is for Mongoose so you can just ignore that however if we removed one of these and changed the industry let's say to something more important like I don't know gaming or something and let's go ahead and switch this over to put hit send it says updated count one and if we go and retrieve that data it does have industry gaming but the name has been removed that's because we are replacing the entire object we'll talk about how to update individual things in a couple episodes but for now this is the way I would recommend doing it so now let's take a moment to talk about the difference between put and post important thing to know is that this is convention you can use either one for whatever purpose you want so it's really up to you to implement it the way you desire but it is important to follow these conventions when you can because users who use your API are going to expect them to work a certain way the way I've done it is I will typically use post for adding a resource so when I want to add a new customer and I'll use put to update a customer or I'm kind of updating a customer but I'm really just replacing it with the same customer with modified data if that makes sense but this is seen as an update action so that's why I'm using put the other important thing is generally when something can be repeated multiple times without consequences that's when you might want to use put and that concept is known as it being item potent so when you're posting a resource when you're adding a customer if I slapped the send button multiple times it might add multiple customers into the database however with updating a user I could replace the same user over and over again with the same attributes and the end result was still the same we updated the original customer so you can slap the send button as many times as you want I think that is the key main difference and you will need to make sure that if you want to follow that structure that you implement it in that way so if you're using put but you're adding a resource well then people might get a little bit confused also another good indicator is if you are providing an ID use put because that's going to be working on a resource that already exists in the database and you're not adding a resource I'm using resource which hopefully you got it figured out by now but it's just a general word to describe the item that we are adding or removing or editing from the database but it's important to know that this is not perfectly agreed upon so here you can see two answers that are literally the exact opposite but I think this is the most important thing so definitely read about this more and the question here is what is the difference between post input and HTTP now you'll also see that put is used to create or replace a resource there is actually a third method that you often see when it comes to this conversation and that is patch if you are updating an item using individual attributes you know you're not providing a whole new object to replace the original that is when you would want to consider using patch and that is a more proper technical update because we're actually just changing the attributes in the database versus replacing the entire thing so we're going to talk about patch here very soon so stay tuned but it's not going to be a whole lot different but still we're going to actually be implementing some of this stuff in a react application so I'm excited for that we'll be doing that pretty soon I kind of got a little distracted with talking I didn't quite finish the code here I still want to have the try catch so I will surround what we have with try and indent these lines here and then we'll say catch and give them a general error so res dot status of 500 and what we want to tell them is pretty similar to the example up here we'll just say error something went wrong and that'll do for now bro what is wrong with me I keep forgetting to put my curly braces I'm so sorry thank you all for watching in the next video we'll talk about deleting a resource which is a lot simpler than this one so we don't have to talk about different options and all that stuff so we're just going to get to it I'll see you in the next video hello everybody in this episode we're going to learn how to delete a resource through our API this one's really not hard to implement but if you screw it up there's a good chance you're going to screw it up pretty bad because you don't want to like delete everything right so we're going to be careful not to do that so we will go ahead and use the delete method the path for this is going to take an ID because we need to know what resource to delete and I do recommend using an ID for this and not some other thing as you'll want to be sure to only delete a single item if you're deleting based off of some custom filter there's a good chance you could screw it up so I think it's best to just not do that so this is going to be pretty similar to the replace one she will say await customer dot delete one the filter is going to be required which is going to say hey we want to match the ID with the request.params.id or as we did in previous videos we could assign this to a constant and then use it so const customer ID is rec.params.id and then this is going to go here customer ID the second thing uh there is no second thing and that's all you have to do you don't have to pass in a second argument because we're not replacing it with anything so we'll just assign the result to a variable or a constant result here and inside of this result we're going to have a deleted count similar to how we had an updated count up above so we'll just say deleted count and assign it to Value result.deleted count we can test this out by getting a resource first confirming that the data is there changing the method to delete hitting send deleted count one you issue it again deleted count goes to zero because it no longer is there and now when we try to get this resource we should get a 404 so that is the process to test this now obviously like all the others will want to do the try catch just to make sure everything is working good we don't have to worry about the scenario where the customer is not found because the only changes that it's going to say deleted count zero but in the case of something going wrong that is where the try catch comes in so overall pretty simple we'll just give a general error like we have been pressed status 500 .json and then error is something went wrong you can customize this however you wish that is your introduction to deleting data overall not too bad so hopefully it went good for you stay tuned for the next video the next one is going to be really exciting we're doing something new we're actually going to be moving over to the front end I'll be teaching you how you can integrate this in a react application I already have a pre-built react application but you can customize it as you wish so I'll tell you how to get all of that in the next video and from there we'll be able to see our customers view their data delete them all that good stuff so stay tuned I'll see you in the next video peace out what's going on everybody this video we're going to talk about how you can connect to your node.js backend from a react front end react also uses JavaScript which is quite nice you only have to worry about one language but there is quite the learning curve for react so if you want to know all the juicy details you can check out my react full series on YouTube it's like 20 hours and I'll get you going in the right direction but we're going to start with the starter repo from that Series so you can clone it you can use some of the code for your project and it'll give you the essentials to start working with a back end from the front end of your application this will allow us to interact with the customers in our API but we're going to have it in a nice visual web page with buttons and inputs and all that good stuff so check out that series I'll try to remember to drop a link Down Below in the comment section and the description all right so here is my GitHub account you can go to my repos and you can search react hot dang there is so what we'll do is we will take this repo you can grab that URL you can clone this somewhere it doesn't really matter where what we'll do is we'll just clone it here inside of documents it'll be a sibling folder to the customers so say git clone paste that web address there we what in the heck I don't want all that junk there we go so that will clone into this repo and now what we can do is we can explore this repo and see what's in it so the main thing then here is the source code is in the source folder and inside of source we are going to have pages and inside of pages we are going to have this customers this is the file that we're going to take a look at which is going to have the information about connecting to the customer's API so go ahead and open this in whatever editor you are using but from this terminal here what we can do is we can actually say npm install which is going to install any of the dependencies for this project once those are installed we can say npm Run start this will open localhost 3000 in the web browser now this is the same port that we had our node.js running in so we will need to change the port on one of these if you try to start your react application when your node.js application is already running it might ask you if you want to start it on another Port but what I'm going to do is I'm just going to change the port on our node.js application so we don't have to run into this issue again so we did that in earlier videos using the environment variable really simple so over in dot EnV I'm just going to change this to 3005. you can really use whatever you want and then npm run start and I'll just confirm and starts on 3005. so there we go when you launch your application it should look something like this and we can head over to the customers page here are our customers now with whatever browser you are using you should be able to right click inspect and there will be a network tab which will allow you to take a look at the network traffic including API requests which can help you find any issues you can also find issues in the console as well so if you go to the console you might see errors here so this network error has to do with course cross origin requests basically the tldr of that is that we're on localhost 3000 our server is actually on localhost 3000 and 5. and the server is like yo these are from different Origins they're coming from different urls and it's going to block those requests by default which can help protect your backend from malicious requests but we can temporarily disable this or allow specific Origins such as localhost 3000 to make requests to the back end to do this from the back end what you'll do is we will say npm install course this is a package which will allow us to easily set these settings up once that is installed you will import this here so const course require course and it's really easy to use all you have to do is say app.use and pass in a call to this course constant we created this will change the General functionality of our backend such that we don't have to worry about these cores issues so you can learn more about configuring your course middleware if you wish just go ahead and research the course package but I'm just going to stick with this very basic example which allows cross-origin requests to our back end now that we have that set up we will run our server again so npm runs start you can open another instance of ultra edit with the command palette Ctrl shift p and then allow multiple instances which you can then check and then open whatever you want inside of ultra edit inside of the source directory where we Define our Pages we also have this shared file which is where I decided to put the URL So currently it's localhost 8000. we'll just want to set that back end port to Something That We're actually using in this case 3005. and save that and there you have it our page is now working it is getting the customers from the database so you can go into any of these and take a look such as this one here this page is currently not working so we're going to talk about why in a moment but the list of all of our customers are working let's test this one out add a customer test test hit add and take a look at that we can even add data to our database let's go ahead and do a refresh just to make sure that data actually persists and you can see it's still there now you can still work with the API directly if you just want to you know check the data make sure things are looking good um you know to make sure nothing was messed up in the front end of things and you can see I've been testing around with some junk data here but yours might be a little bit more clean now the functionality to make that home page for the customer's work comes from the customers page inside of the source file the reason the individual customer is not working just has to do with the ID because if you scroll through here we are passing to slash customers the customer dot ID but coming back from mongodb it is actually an underscore ID so if you add that underscore there and save it an individual customer page should now work and you can see the name in the industry pops up now we should have that full functionality so we can say John Cena industry is I don't know wrestling uh being invisible and we can save okay so if something went wrong just go ahead and check the network Tab and see what's going on so head over to the network we'll try to save this data we're getting a 404 not found and this actually just comes down to the request method which I had in the front end defined as post so what you can do is just alter the request to be a put method since that is what our back end is expecting so that functionality can be found in customer.js page and the method is post let's just go ahead and change this to put now we should be able to change this data and have it save so being invisible hit save and nothing shows up here which is another problem we're going to address here in just a second but if you do a refresh you can see that the data actually did go to the database and was saved so when we go back to our list of customers you can see it's saved as John Cena so the problem was when we saved it it just showed a blank screen instead of showing the new updated data and this has to do with actually our API design so from our API if you take an ID you can get that individual customer and we could change that data with a put and let's just go ahead and copy this customer data and we will include that in the body we'll go raw Json and paste that here if we update this The Returned data on a success is an updated count one and what the front end code is actually going to do if you look through the code is it's going to look for the updated customer data and it's not going to get that so it doesn't know what to do with this and the screen is blank so we're going to talk a bit more on another way of updating data in the next video but before we end this video I just wanted to go over a little bit more of the react stuff so you can have a better idea of how it's working and you can edit it yourself if it's too much you can go through the react series as mentioned at the beginning of this video the main important thing to understand is that pages are generally tied to URL structures whereas components are little pieces inside of pages that can be reused the starting location really is index.js which will then basically immediately invoke app.js so this is where the bulk of the starting code is so inside of app.js you can scroll through here don't worry too much about the refresh tokens and stuff for logging in that's just for some basic auth the thing you should worry about now is the routes so these are the different URLs and the different components that will be hit when you visit those URLs so when you visit a customer it's going to render the customers page if you do customers colon ID then it'll visit an individual customer so then you can go into that page so go into Source pages and then whichever page you're interested in such as customers and inside of here you can scroll up to the top and the main things are going to be use effect and in this scenario a custom use fetch hook and this is what's going to actually make that web request so we Define a URL here scrolling through we invoke use fetch Define what method we want and any headers we want and that is how we make a web request the call to use fetch is actually going to return a function which we called request so we can then invoke request inside of this use effect thing so a use effect does is it'll execute once when the page loads based on this value here which is called the dependency array which is currently empty which says hey we want to execute this use Effect one time when the page loads now clearly if you've never done react this is probably like WTF this makes no sense but I agree so use effect executes once and that is just going to execute requests what is request well actually comes from use fetch which you can jump into Hooks and then use fetch if you want the details of but it's basically just complicated code to make a web request so you can see fetch here with the URL the method headers and body and what happens after it's done so far so good when this is done the data variable is going to contain the customer's data so we can later on in our code use that so down here we can say customers.map so for each customer we want to display some HTML specifically a link to that individual customer with the customer's ID so the individual customer is the parameter for this Loop you should probably understand a little bit about mapping in JavaScript so this is kind of like the iteration variable each iteration is going to be talking about a different customer which is how we can make General code to discuss customers and it's going to substitute in for each customer ID so for every single customer we're going to have a div with that link so far so good and then we have this add customer component which you can explore inside of the components if you wish so that's kind of like the basics of how the page structure works it's going to be fairly similar for an individual customer once you understand those themes it's pretty similar across all the different pages so you can go up here it looks like this one might actually be a little bit different because it's doing the fetch inline here instead of using that custom use fetch hook either way is fine so yeah that is the introduction here is the update customer function which we're actually going to go into in more detail for the back end side of things in the next video hopefully this video was helpful so far I know this was a ton of information and not really a comprehensive react video but I just wanted to kind of give you a shortcut to having a functional full stack application so you can see the end result then if you want more I've given you the resources to make that happen you can continue watching this series for the back end and you have that full react series on my channel as well thank you and stay tuned for the next video peace out hey everybody Welcome in the previous video in the series we ran into a situation where when we update a resource through the API we get an updated count of one but sometimes instead of just a count you might actually want to retrieve that new object so what you could do is you could then make a get request to get the updated data or there is actually functions that you can use that will automatically get that data for you so you can return the updated data that's what we're going to talk about in this video so here we are looking at the code for our put method we are using await customer dot replace one this returns a result object which has a property modified account and you can see what that looks like down here so what you could then do is then take the same ID and make a get request to retrieve the updated object from the database but it's a little unnecessary since some tools are already given to us to do this and instead of using replace one what you're going to use is called find one and replace find one and replace the arguments for this are going to be very similar so we're going to have that query there the ID being the customer ID and we're going to have the body to replace that data based off of what we have here it's not going to work exactly the way we expect I'm going to show you the functionality by default if you have it just like this and then I'm going to show you a change you can make to make it probably what you were expecting additionally we're going to want to remove this modified count so instead of having a result object with various things describing that update it's going to be the data from the database so we'll save that so first let me retrieve some data from the database you can see this is the customer right now if we went ahead and changed this data with the new code changes we have on the back end let's go ahead and just I don't know we'll just change this to Papa John's and the industry is in pizza it's not an industry I would classify that as an industry so then what we need to do is we need to change this to put so we're actually making that update we hit send and again you don't need to have that ID since the ID is being passed in here but I just copied this and pasted it up here so you could remove this all together but you might notice that the return data actually has John Cena update which is our original data if we then sent this again it now has the Papa John's with the industry pizza so this is kind of strange it's like one step delayed so we hit send it has the original data but if we get the data from the database it has the updated data so what find one and replace will do is it will take your data change it in the database and return to you the original data I don't know why it works that way by default but there's one flag you can change to make it return the updated data instead of the original data so this is a really easy change I'm actually going to just scroll over and add a comma after request.body this is going to be an object and one of the attributes on this object is called New if you want to return the new data then you will set this value to true so now let's give this a shot we will change the data updated again hit oh sorry I need to change this to put real quick so this is the current data we update it and we get the new data let's just test it again hit send and there we go we get the new data this little change will actually make our application on react work a little bit better based on this update customer here if we scroll down to the response data we're setting the customer to data Dot customer so this comes from the API you can obviously change the react code to do whatever but based on the default behavior that you get from the repo code I shared with you it's going to take the new data from the API and change the current customer data so it wasn't working before because it was basically sending the customer to the changed count which was one so that doesn't make any sense what this means now is when you visit a specific customer on our react front end we can go in here delete some data hit save oh the change is stupid I forgot to change the actual attribute name on the back end so he has a dumb mistake so let's go ahead and take a look back at our back end and we will change this from updated count to the customer or another shortcut you can do is just change this constant here to be called customer and then instead of having customer being customer you can just put a customer in here directly like this and that'll make a property named customer with this value the other thing we'll need to do is remove result here since we no longer have that or you could just change the name of this to customer so you can see that on the back end here and if you want if you want to see any errors you could say console log e Dot message trying this now we change this to some value such as Papa John's updated hit save and you can see it seems to have worked so when we refresh we see that new data and we can change it to something else so I successfully retrieve the new data from the database we update and it saves the change to the database as well let's start try changing the industry and let's change the name at the same time we'll hit save and it seems to be working that is now the new data so cool everything appears to be working let's make sure delete Works yes it does so we can delete all this trash data and there you go you got a pretty functional crud application is it perfect I mean I made it so probably I joke there's probably a lot that I could improve on this application but this will give you the start for create read update delete on the back end and the front end and react now you just need to sharpen up on your react skill so you can fully understand the react code which I do have a series on not trying to continually advertise that but for those of you who didn't watch the previous videos there is a long react video on my channel there's an all-in-one that's like 12 hours and then we're gonna have a part two which is eight hours so definitely check that out oh that's all the energy I have for making videos so I'll catch you later thank you so much for watching this video stay tuned for the next one appreciate you be sure to subscribe what's going on everybody this video we are going to be talking about working with nested data for mongodb through Mongoose so this is basically just a change to your schema but if you've never really worked with nested data or you're coming from a relational database background it might be a little strange or a little bit of a learning curve but it's really not bad all right so here we are in our database we have one customer and our customers collection and when we edit this we have the ability to add if you click this little plus you can add a field after name and let's just go with an example they have some orders and the value for this could be an object where an object can have multiple attributes so now we can do the same thing we could have a description for that order which could be a string and let's go ahead and add a few it after this which might be say the amount in cents I've kind of grown to like using cents for money so this would be a different type you could use decimal 128 and just use dollars as well but I'm just going to go with N64 here so let's go ahead and say that Papa John's personally purchased a MacBook Pro from me and the amount for this was 100 000 cents which I believe is like a thousand dollars not bad so there is our new object we can update that and there we go we now have an orders which is an object what if we wanted to take this one step further and have multiple orders well then instead of this being an object it would be an array so we can edit this and change this from an object to an array which kind of screwed up our data but it's all good same concept here instead of this being a string we would make this an object and then do the same exact thing so now you can have multiple orders description MacBook Pro amount and sense and we'll go with 100 000 there and then we'll go ahead and add a instead of add field after a mountain sense if you go up to the zero index 0 you can say add item after zero and that's going to add a new index so this is going to be the same concept so instead of this being a string we'll change this to an object and clearly doing all this by hand is quite annoying so once we have our code written out it'll be a lot easier so we also sold Papa John's some garlic sauce for their ingredients we sell everything and we'll go ahead and add a field which will be amount and this is going to cost them a hundred bucks and then update all right sweet so now when we get our customers you can see this is what the data looks like if we wanted to update this data in the database basically we would start by copying this object pasting that here and then going in here and changing any data let's just say instead of a MacBook Pro is actually a MacBook Air my bad probably didn't know that until after I sold it to them though Get Wrecked and then change this to put go ahead and hit send and when we look at the response here it seems like all of the orders disappeared so when you manually add those orders to the database and retrieve them through our API it works because it just goes and accesses whatever's in the database and displays it through the API but when we're actually updating data or doing pretty much anything else the orders are kind of unknown to the application so we need to do is we need to go into our schema and add that structure and say what type everything is supposed to be remember Mongoose is basically the mapper from mongodb to JavaScript objects so we need those to be in sync so head over to our customer.js and here we have a name and an industry well now what we can do is we can go in here we can add another attribute which is going to be the orders this is going to be defined as an array which you can do with square brackets and inside of this array you can define an object so it might look like this here we go and now we'll Define the attributes for what this object might look like we can have a description which it will say is a type string and then we can have amount in sense which will be number so give this a save and additionally you will want to check over your app.js wherever you are saving that data to the database in our case it was the put but you also probably want to check your post method you will want to confirm that the data that you are using to save to the database is the entire request body and not just select attributes if it's select attributes then you'll need to go in and manually add any of the ones you want added so this one looks good we're just going to take the entire request body and then let's check the post method as well scrolling through here you can see that here and we are creating a new customer with the request body that means now when I send this data in theory we should get the entire object back from the database perfect so yeah it looks good let's go ahead and try adding one so we'll go to post uh let's give this guy a new name we'll See's also in the industry of pizza although now that I'm thinking about it little C would be a pretty cool child name of mine anywho let's go ahead and sell Little Caesars themselves some junk we sold them some cheese that's a good price and garlic sauce send oh snap oh that's because we still have the ID on there that I copied over so we don't need that crap get rid of that junk hit send the ID here is like stuck so I don't know what's going on let me just make a new request I don't know what I'm doing okay so I we'll post this data and confirm that it goes in the database looks good so we should now be able to get all of the customers and there we go taking a quick peek at the database we'll do a refresh we can see this data and you can expand any one of these so go into orders and you can see the data here also good to note that there is an ID on that nested object which is really handy because basically now we can identify that order by an ID so that's pretty cool so if you wanted to update this specific order you can do it by ID and we'll check out the other one down here as well cool I love it that's all I got in this video in the upcoming video we're going to talk about a very important method called patch which you'll often see when you want to update just parts of an object instead of copying the whole object and changing it so stay tuned for the next video it's pretty important I'll see you there peace out hey everybody Welcome in this video we're going to be talking about the patch method this is used to update a resource but it is different than put typically put will be used if you are replacing the entire resource or whatever you're working with in the API you can use this technique to update data basically copying the whole object modifying a few things and then sending the updated object back to the API and this is often done but sometimes you'll just want to say exactly what you want changed and not have to copy the entire object originally imagine I have a record in the database and it's for a customer it has their name their address and then nested 50 orders for example you might not want to take that entire object and then just change one individual field and send that entire object back it might be a lot of unnecessary effort and data that needs to be transferred so with very small records doesn't really make a huge difference but as your records grow it can make sense to just use patch and update specifically what you want so if I want to update a user we need to include the entire object and then change whatever data that we want changed this can be a little annoying so the idea of patch is if we switch this to patch we could just change what we wanted so for example we could exclude those orders and we might just want to change the industry to something a little bit more readable like so but obviously if we do this now it's just going to delete everything and leave us with just the industry of pizza and actually we're getting an error well it's not working because we don't have patch implemented so if we did the same equivalent with put it's just going to replace everything and now we just have this customer with just an industry of pizza kind of silly so what we're going to do is we're going to go Implement patch so I will Define this probably after app.put since it's kind of related to updating data so say app dot patch and this will also be at API customers colon ID and we'll have an async callback here request and response and here is the function code wise this is actually going to be almost identical to put we're just going to use a new function called find one and update so what I'm going to do is I'm actually going to copy this code here paste it down here now all I have to do is make a few edits find one and update there we go so if you're just jumping in because maybe you search this we'll go through the code here in a moment notice we still use the same arguments so we can find the customer by its ID we provide the entire request body and then we return the new updated object from the database all right cool so let's go through this line by line real quick just to get a brief overview so the very first thing we do is within a try just in case something goes wrong we get the ID passed in through the URL we find that user and update that user and then we're just console logging the result for our own sake and then we send that back to the user inside of these curly braces which will make an attribute of customer have the value of that customer object so let's save this give it a shot let's first start by going with a very simple example by first creating a name in an industry so this person will have the name of Caleb and the industry of YouTube so let's go ahead and update this user so this is the new customer in the database so let me just get that just to confirm we're not getting anything weird here looks good and now let's go ahead and patch and say we just want to update the name we can say Caleb Curry remove that comma there hit send and you can see the full response is the full object so it appears to be working which is really cool that's your introduction to patch overall not too bad we'll be talking about here soon is how we can edit nested data so stay tuned I'll see in the next one peace out welcome everybody to your node.js Series this video we're going to talk about how you can edit nested data through your API there's probably various ways you could approach this we're going to talk about one of them in this video but if you have some other ways you can definitely drop suggestions down in the comments section so here we have some example customer data and you can go ahead and set this up to be the same in whatever database mongodb in our case so that we have a single customer here with a nested orders so the orders is set up to be an array of objects the attributes for the orders are the description and the amount incense and you can see that it's given an ID and this is interesting and important because this allows us to grab this order by its ID so that's how you can uniquely identify this order we created the API endpoints to create this data in earlier videos so definitely check that out if you need going into mongodb we can see that information here we have that order what I want to do is I want to actually create a second order so you will need at least two just for me to Showcase a potential problem so if we select edit and then down here for the object we hit the plus and say add item after zero and the type of this is going to be an object so the first attribute we can make be the description this will be a string we'll just say test two and then we'll add another attribute after this so the description and then the amount incense and doesn't really matter just going through an example and I want to make sure this is typed to uh we'll just match what the other one is which is in 32 so into 32. and give us some value Okay cool so now this person has two orders in their data so that should be shown when we get the data from the API as well and you can see both of those there it is possible to use the patch method to update a customer and we can just update the individual orders property the key thing to know here is that the way we have it set up in our code it's going to replace the entire attribute so let's talk about what that body might look like if we go in and type body raw and then Json and we'll drag this down a bit so we have a little bit more room we might pass an object with a property orders which will be this array and then we would just change the appropriate data that we wanted changed so let me just grab that if I can control this and we'll paste that there so now we can just change this so for example we could say test one went great and we'll just change this to something like updated same thing down here test two updated we will also need that user ID so we will take this here and that's going to be provided in the URL here so hit send and we can see we get the new customer object back and the code for this can be found right here so app.patch that is the code that we are using the problem with this is if we want to just update a single order it's not going to work the way we might expect so let's say we just wanted to update this first one so we remove the second one in the body that we're sending and we'll just change this to test one updated again well what this does is it takes the orders attribute and replaces the entire thing so it doesn't really work the way you might initially expect a patch to work based off of our previous videos where you just provide the things you want to update in this case it considers this orders as a single unit and we'll replace that entire value with whatever one we provide so hopefully that makes sense it can be a little bit confusing especially if you just see data disappearing and you're not entirely sure why so there's various ways of working with nested data and in some scenarios you might not have nested data but rather a different database or a relationship to a table that has the orders so that could be set up in mongodb but typically with mongodb you're going to have nested data so what we could do is we could figure out a way to uniquely identify an order which we have this ID right here and we could start creating API endpoints to work with order IDs as opposed to customer IDs such as this one here and then we can change the functionality to just replace that individual order so then when we have the order here it's just a single order but the original data in the database keeps all of the other orders and only that individual order is modified so hopefully that makes sense if you want to get started with this it's going to be pretty similar to The Way We access customers where we pass in an ID but now instead of API customers and then the customer ID we could have API orders and then the order ID so let's go ahead and structure that in our code we will head over and I'll go ahead and create a new endpoint here we'll say app.patch I'm going to zoom in just a little bit so far so good so let's go ahead and Define this endpoint here so we'll say slash API slash orders slash colon ID and then we'll have an async function which will have the request and the response and let's go ahead and Define that body here let's go ahead and just first console log that ID which we can get with Rec Dot params and just to make it easier to refer to this let's go ahead and say const order ID and assign it that value so we can just keep it a little shorter and just use order ID so we will use a try and then we will catch e within the catch we will just call in Sol log what the problem was e Dot message and then give a general response to the user show whereas dot status 500 dot Json providing an object here that can have an error property and then some message like something went wrong similar to what we've done above here okay so we have the general structure now let's talk about what goes in this try well we can use customer dot find one and update this is going to take a few different values it's going to be very similar to what we've done here so if you want to pause and give it a try feel free let's go ahead and take a peek at that so the first thing is we grab the ID by customer ID we provided a new value in the request top body and then we said new true to return the new updated data from the database so let's go ahead and do something very similar to that here so I'm going to actually break this down into multiple lines just to make it a little clearer we'll say the borders dot underscore ID in quotes and we haven't talked about this yet but basically what this does is it allows us to inside of the customer go into the orders attribute and then into that order's ID because regardless of what we're trying to access mongodb is going to return the main document since we are grabbing an order by an ID and that order is within a customer document the document that's returned is going to be the customer so we can Traverse into the different attributes of that customer using this pattern where we have whatever attribute or property we want to access Dot and then whatever the next one is and so forth so we'll go into orders and then dot underscore ID now we quote it because this isn't valid syntax so you'll probably end up using quotes when you want to do the nested stuff so that's the first thing the next thing also is going to have some new information we are going to use the set attribute and provide an object and the object property is going to be orders dot dollar sign and then this is what's going to get assigned the request.body so again this is probably new potentially a little confusing what this dollar sign does is it refers to the order that the ID matched so basically this first line is saying hey let's grab the customer that has the order with this ID order ID and then to refer to that individual order we go into the orders property and use the dollar sign to substitute in that value and then using request.body we can then set new values so a little complex but not too bad once you see it a few times but it did take me a couple tries to get it set up correctly and then the third thing here is going to just be new being set to True let's go ahead and assign the result to something so we'll say const result and let's go ahead and console log result if result so if there is something returned from the database meaning it was updated we will give back a response of that result otherwise we will do a 404 so response.status 404 dot Json error being something went wrong all right so let's see if I got this all right without any problems probably something in here but let's give it a shot so now we can grab an order by its ID so go ahead copy this value and what we'll do is we'll use API slash orders pass in that order ID and now we don't have to do all this extra nesting stuff so we can just remove this and just provide that object so we will just clean up this formatting a little bit and now we'll just say updating directly and maybe change the amount as well hit send let's see what happens and you can see we get the new object back it has the updated directly and the new amount so it seems to have worked and notice it does return the full document as mentioned earlier so you're always going to be working within the original document so you'll need to Traverse appropriately when you want to access inner data let's try this again but let's just make sure we first have multiple objects within the orders just so we can make sure this is working so you can do that through the API or I'm just going to do that manually here so we'll go ahead and add nine I'm after zero this will be of type object the first one is going to be the description test then we'll have the next one which will be in 32 and this will be the amount in cents 500. now if you want you can also have the object ID on here so add a field and this will just be called underscore ID the value here is just going to be of type object ID and it'll generate a value there for you so hit update make sure everything looks good so we have orders and two objects inside of it so now from a new tab we can go ahead and request to just make sure we're getting that data the way we expect cool and now let's refer to one of these let's go ahead and grab this object ID we'll copy that and go back to our other requests here change it and now let's go ahead and say we want to test again and we'll change the amount of incense to five now we want to be careful here because I want to make sure I'm providing the right ID here hit send okay and this is the full customer so we have the customer ID the two orders with the updated data and the name looks good what happens if you don't provide an ID let's go ahead and hit send and it looks like that works as well but notice something here this is actually a different ID so the ID was changed it was replaced so if we hit send again it doesn't work because we can't access that same object this is weird so to us it's like the same object but in mongodb's eyes we just basically created a new one it has a new ID and the old one was replaced so if you wanted to fix this in code so you didn't have to provide the ID as an attribute there's a way you can do this I don't know if it's the best way but it's a way that worked for me and that is to just take that ID that was provided in the URL and add it to the customer that we're updating in the database so you can just imagine it's already included in the body so request.body dot underscore ID is assigned the value of order ID and now it's as if we included that order ID in every request and we don't run into that problem let's test this out getting the latest customers I will grab one of these IDs copy that bring it over here and that's the ID we're going to provide in the URL but we're not going to include it in the body and when we hit send it works and it has the same ID returned so we can adjust this without having to get a new ID every single time perfect hopefully that was a helpful introduction to modifying nested data there's probably some good information in here that you could research further if you want but that's all I'm going to be covering in this one next one we're actually going to be talking about something new which I'm quite excited for we're probably going to introduce typescript and how we can bring that into our project really excited for that hope you are as well I'll see you then peace out hey everybody Welcome in this video we're going to talk about how you can retrieve data using nested object IDs instead of always grabbing the outermost document by ID at the end of the previous video I did mention we'd be talking about typescript in this video kind of lied it was an accident I swear I forgot about this video so we're going to talk about that in the next video pinky swear it's not a pinky pinky swear unless I forget about other videos let's get started this one should be pretty easy so in the previous video we talked about how to update orders by an order ID and this would probably have made sense to come after this video because what we're going to talk about now is how we could get data by an order ID currently this obviously doesn't work because we haven't implemented it so we get an error but this seems like something we would likely want to do since this Builds on a lot of principles we've already talked about go ahead and pause the video and try to build it if you are interested otherwise I'm going to jump in and code it now so let's go ahead and open our editor and we will create a new endpoint after this one we'll push everything down and say app.get very similar structure to what we've done a thousand times by now so API orders colon ID async request and response and we'll do this within a try which will have a catch we'll just call the error E and the error will just console log e and then give a general error message as we've done in the previous examples so it'll look like this lovely cool all right so now let's open the try and inside of here we'll say oh wait customer and we can use the find one method this will take a filter and we're going to go into the orders of the customer and then grab it by ID so very similar to what we did in the previous video when we're updating an order this value itself is going to come from request.params.id so that's what we're going to provide in the URL this can be assigned to something like result and then we can check if result has a value so if a result we will send it back to the user so result.json and we'll say result else status is 404 and we'll just give a general error message but we can say it wasn't found so order not found and that would actually make sense to do over here too so order not found unrelated but yeah back to what we're doing make sure to Define this as an object like so now let's test this out we should be able to get a specific order and you can see we have it here now this Returns the entire document that's always the way it's going to work because this order is part of a customer document we get the customer back and that's fine in many cases so you can structure your code this way or you can Traverse into this orders array and grab just what you're looking for but just to kind of illustrate this let's say we grabbed this other order ID copy that paste that here we're no longer need this body for anything so you can just kind of ignore it and it gives us the same thing I'm probably honestly fine returning the whole customer just let the user do whatever they want with the data if they just want that object then they could just say result dot orders and then grab the one with the correct ID however they want to do that so I'm probably just going to end it there but just so you know there is more you could do you could do that traversing client side using this API or you could do that traversing inside of your code as well and just give back this object directly that's all I got for right now so stay tuned for the next video where we're going to talk about typescript peace out what's going on everybody this is a video I've been very excited for in the series we're going to introduce typescript how to bring it into our node.js project without making it too crazy complicated so first let's talk about what is typescript it's a language that transpiles down to JavaScript so the typescript doesn't get executed in the browser directly instead it's converted to JavaScript and then that is executed in the browser so the end result should be the same still JavaScript but we get a lot of added benefits that typescript brings specifically static typing the ability to give variables types ahead of time and this is going to bring a lot of our typically runtime errors issues that show up when we run our code it's going to bring them up sooner at compile time or transpiling time when we go from typescript down to JavaScript we're going to see errors we're going to be able to fix those problems and our code way earlier a lot of projects today use typescript most likely if you're going to be a JavaScript developer working in node or react you're going to want to familiarize yourself with typescript so this video is going to not be so much about the typescript language but more about setting it up so there's a few steps to bring typescript into your existing node.js project that's what we're going to talk about in this video in the next video we'll start learning about the actual typescript language and the different types and all that stuff so to begin we're going to install typescript so we'll say npm install and we're going to use either dash dash Dev or Dash capital D typescript and this is going to install it as what's known as a Dev dependency which is slightly different and that's because we're only going to need typescript in development as mentioned typescript doesn't run on the server it's always going to be JavaScript which is the final result so once this is installed you can check out your package.json and you'll see this new Dev dependencies typescript and then whatever version you can also install typescript globally to get some various commands specifically TSC so you might already have it but if not you can say npm install Dash G for Global so not for this specific project but for your entire computer and now you should have the TSC command available to you pretty simple so to begin we can initialize a typescript project but we don't have to start everything from scratch because we can actually do this within our existing project so we'll say TSC dash dash init and it's going to create a tsconfig.json so whenever you have a tsconfig.json that means you're working within a typescript project this is going to be the general structure there Target's going to say es 2016 yours might say something a little newer like es2020 it doesn't really matter for what we're doing and then just some of the other defaults like such as the common JS which I think we talked about in one of the very first videos in this series so you should now see that file in your project and there's going to be a lot of different comments in here so you can ignore a lot of this but this will give you some of the different options if you want to look through and see what's possible okay so we got typescript added to our project now what do we actually do what's it yeah how so we can say TSC and then the name of the file and we don't currently have a typescript file so we currently only have the JS file so when we issue this it's going to say that it is a JavaScript file so you need to change this to a typescript file by renaming it to index.ts there's also the ability to change it to enable to allow JavaScript if you want to set that up but there's not really a good reason to do that if you want to get the benefit of typescript so what I recommend is to change your file names to dot TS so inside of our source we're going to just rename this to app did I really say index yeah I just realized app.js instead of index.js but that's fine so we'll just say app dot TS I think this command would have said the same thing even if it was a random file I think I just noticed is that it ends in a DOT JS and complains so now that we actually have an app.ts we should be able to compile this with typescript before we compile we can also rename customer JS so we will rename to customer.ts now you can compile your code with TSC and this is going to take a typescript file and transpile it down to a Javascript file so taking a look over here at the files here we will get an app.js so this was generated from the app.ts and you can look at it and you can see it's very computery looking so it's kind of based on app.ts but it's not going to look exactly the same now if you're getting errors I'm going to show you a little trick now this is not by any means recommended but this will at least let you compile you can say TS no check and that's going to ignore the typescript error so you can follow along with getting the typescript added to your project this is kind of like a hack it's almost as if you're just using a regular Javascript file so it's not really recommended if you don't have to use it but just given that as a tip if you see that anywhere in the wild that's what it means to compile everything you can say TSC Dash p for project and then identify where that project is based on the TS config file as we mentioned this identifies your typescript project so that is how you would compile everything now when we do this we get a bunch of Errors pop up and that's exactly what I was talking about with doing this no check temporarily just so I can finish getting everything set up then we can go back and figure out how to fix these errors so I'll just say TS no check and I'll do something very similar for the models file so going into customer.ts I'll go ahead and add that line as well so that's what it's going to look like so those are all saved and now what I want to do is I want to compile the project again and we're not getting any errors pop up and you can see that this will generate a customer.js and it's going to generate an app.js so any of the typescript files get compiled down to JavaScript files and additionally there's a watch option for this so you could say dash dash watch and any changes made is going to refresh that compilation so that can be an interesting step so for example I could just change this real quick and you can see It'll retry to compile but I'm going to change that back and save and there we go so every single time that's going to generate new JavaScript files you are still going to need to run those JavaScript files if you want to see that change actively so to test this out I can open a new git bash window change to this location so we'll change into documents and then customers and then we'll say npm Run start this will start running and our app is now listening so let's go ahead and just see what happens when we access some endpoint let's go to postman and we will just go to the main endpoint this just says welcome if we then head over to app.ts find that endpoint so scrolling through here we have that here and also we have a lot of bloke code that we don't really need anymore so we can clean it up but not to get too distracted so let's go ahead and change this to welcome with two exclamation marks hit save this will refresh our server we hit send on the endpoint again and you can see it has welcome with two exclamation marks so nodemon caught that change in our Javascript file and refreshed our server and you can see that here restarting do two changes so now it's like this two-step process we change our code we save the typescript compiler which is watching will then generate new JavaScript code nodebon is watching for JavaScript code changes that'll refresh our server and we get those changes live so at this point you have typescript installed on your project but there's a few issues one the setup commands and stuff are a little wonky and two we haven't actually talked about any of the typescript code we just had all those errors that we just ignored so that's we're going to be talking about in the upcoming episodes how it can continually improve on this to actually get the benefits of using typescript so stay tuned for the next video and peace out welcome back everybody this video we're going to continue our discussion on typescript going through whatever else we might need to get it up and running in our application I'm going to give you a few tips to make it easier as well so let's just get started so to begin we're going to continue to execute our code the way we did in the previous video which is to use TSC P for project passing in our config and then dash dash watch which will continually refresh the JavaScript files whenever there's a change you may see other approaches out there for example a very common one is TS node or TS node Dev after recording this video I learned that node mod actually supports typescript so you could just say node mon Source slash app.ts and that will compile and run your code and it'll be in watch mode so any changes will automatically refresh that server so you can see those changes right away and that's made possible thanks to TS node behind the scenes so you can look that up as well but we're not going to get into that in this video and that's okay it's just another way of compiling and improving the overall Dev experience for typescript but our setup's working pretty good so what I'm going to do is just go into our package.json and for these scripts here I'm just going to add a new one so that way we can just execute this really quickly you can call us whatever I'm just going to call it watch and this will have the value of this right here so now I should just be able to say npm run watch and then it will start the compilation in watch mode now if you do go down the route of TS node Dev I think it has the ability to do the compilation and running all within a single command it'll just compile on the fly so that might be handy so now that we can run this and see our code just like we had in the previous video and we can start making changes to our code so the very first thing I want to do is just remove this line and this is going to bring up the obvious errors in our code now to see these I'm just going to switch over to the other terminal and the error says cannot re-declare block scope variable Mongoose so we're going to talk about the fix for this but we're going to change a lot in this file and in the process this error will go away so specifically the problem is rooted in this line here and we can actually change the way we are importing so instead of using a require we can use an es6 import state moment which we talked about at the very beginning of the series and said we might see them later well here they are so we can say import and inside of curly braces exactly what we want from Mongoose and then inside of the curly braces we are going to import schema and model so specifically the schema refers to this here and then this model refers to this here this means we no longer need to prefix these with Mongoose since they are available directly and just like we changed the import we can change the export as well so instead of doing this module.exports which is kind of confusing and I kind of don't super get them we can use a regular export for es6 modules and what that's going to look like is Imagine assigning this model customer customer schema to something if we wanted to identify this we would most likely call it customer and that's exactly what we were doing originally if you take a look back at app.ts we were importing what was being exported from that file as customer so this is the same concept but now what we can do is we can just say const customer and Export this so we are now using the Import and Export statements which in my opinion are much more clean and easier to understand so now all we would need to do is import customer in that other file which is going to refer to our collection so over in app.ts if we remove this line here it's going to freak out because we're going to have tons of Errors ignore those all I need you to pay attention to for now is that it says found 26 errors and what we could do is we can replace this line on line three with the new import so it will look like let me go ahead and just go down to the next line import customer from and then give that same path use of above dot slash models customer and then we'll just remove this line altogether save and it still has 26 errors and hopefully everything just works the way we expect now just to check that things are working the way we expect you might not be able to very easily because you got all these errors and you'll have to go through all your code and assign types to everything so it would be nice if we could do that no check thing but just for you know these problems and you can do it line by line or an alternative if you want to learn the line by line one you can just look it up but what I'm going to do is show you something inside a TS config the important one here is no implicit any set this to false now I'm not saying you should do this I'm just saying this will allow you to get rid of these errors it's basically just going to reduce the benefit of typescript but it does allow us to code a lot easier so we'll go ahead and uncomment that I guess I'll bring that back to there and then as well as this use unknown in catch variables you can see we're getting errors for ease of type unknown which is going to be the default for exceptions and what we can do is say use unknown to false and that should get rid of those errors as well making sure to uncomment that line as well so some strange changes if you're new to typescript you might just be a little confused but the main thing you should know is just set those to false to get started and then maybe when you go into production change this to true to make sure you're not missing anything important but for now it is good our import appears to be working and we have zero errors you can see that our server is still running so let's give it a go make sure it's still working the way we expect here we can go to logos 3000 API customers and see that we're getting some data everything appears to be working the way it once did and now what we can do is just continue to build on this by replacing these require statements with import statements if you wish and then go in and assign types to the different variables now one more comment on imports and exports you might sometimes see it like this where there's no curly braces and whether or not you use the curly braces depends on how you define it in the code that creates that variable so you can see we defined that here and we have the option to pass in another keyword here called default and if we're only going to export one thing from this file this is typically what you would see so export default and then you wouldn't actually need to give it a name at all so we'll just say export default model and now inside of the calling code app.ts we can name it whatever we want so that is another way you often see it or to build on this a little bit more you might see it like this const customer is model customer and then customer schema and then down on this line you will just see export default customer and now it's a little bit cleaner on the naming because you can see why you might be expected to name it on the import side of things but this will allow you to basically name it whatever you want you could name it just Capital C whatever you'll just need to go change your code appropriately because we have it referenced as customer everywhere so either one of those is fine a default or a non-default import is totally okay thanks for watching this video on some more typescript import export stuff hopefully it was helpful and not just a bunch of junk thrown at you this stuff can be a lot takes a while to actually integrate typescript into your project definitely a lot easier to start from scratch with typescript so if you're going to consider using typescript maybe just start with it and it'll be a lot easier to manage but that's all I got in this one stay tuned for the next one where we're going to learn some more thank you and peace out what's going on everybody we're finally going to talk about typescript types so we got it all set up finally fixed some of the most pressing issues and now we will start applying some of the typescript stuff okay so now that we want to start talking about types the easy thing to do is just go into your TS config and where you have no implicit any set this to true this is basically going to force any implicit enemies to be established as some type what is an implicit any well consider any to be a type and the word implicit means kind of like automatically by default everything is going to be of type any and any is basically the most useless type it doesn't actually give any type checking it's basically like just ignoring the typescript rules now as you look through all these problems it's going to be the same one repeating over and over specifically request and response so what we can do is we could actually type these to something and fortunately requests and responses are going to be pretty common so it's a type we're going to reuse for pretty much all of these so much so that there's already types that exist for this so just to make sure we have everything we need you might need to say npm install at types slash Express go ahead and install that and that's going to install the types needed for express it says added eight packages so it did something and now up here and yeah I have requires and imports mixed no big deal I'm not going to worry about that right now I want to move on to these types what we can do is we can import the types so we'll say import request response and that's all we're going to need from Express and now to say that something is of those types we can use a colon so let's go to our first endpoint and we have request and response we will say request is of type request capital r there and response is of type response running this our errors go from 20 down to 18 aha so far so good so let's go ahead and do that for the rest of our methods so it's going to be pretty much exactly the same I'm trying to decide if I want to show you guys this on camera or just skip to the end but this is part of the process so just go through this and basically as I'm doing this I guess I could just explain what this does so this will basically say that these parameters are of these types and if you try to access some property on this parameter without it being defined in the type you're going to get a typescript compilation error whereas normally that would have been a runtime error saying something like oh property not found on this type or something along those lines now you'll see that error before our code even runs so it's going to drastically reduce the number of runtime errors so it's important to understand the difference between a compilation error and a runtime error so a compilation error is something you will find at compile time or at the time the typescript code is transpiled from typescript down to JavaScript you can think of that as a form of compiling those are compiling errors whereas runtime errors are exceptions typically by typos or something really stupid that's very easy to prevent and that's one of the reasons a lot of people haven't really enjoyed JavaScript as much as they could some people like the dynamicness of JavaScript but I think in general most people prefer the static typing of typescript it does make coding harder though because now you have to type extra and you have to know what you're doing kind of ahead of time all right save found zero errors lovely so if I went in here and said console logrequest dot tacos you can see property tacos does not exist on type request so it's just not even going to let me execute my code where normally that would have given an undefined and could have led to a potential runtime error thank you so I need to work on my posture oh my gosh that's all I got in this video that's how you type requests and responses stay tuned for the next video I'll see you then peace out what's happening it is episode 29 we are so far in this series I was going to say so close to finishing this series but at this point I haven't told you guys how long the series is going to be it's actually only gonna be 30 episodes so just an introduction to node.js stop it there and then if we want to do more let me know in the comment section below what we're going to be covering in this video is types inside of node.js we're just going to go right into applying these so we're going to use custom types for Mongoose and I'll talk a little bit about how it works so we are going to be working in this customer.ts file and just to get a little bit more practice with types we're going to first learn about interfaces interfaces are kind of like types they describe what the structure of something is supposed to look like now I will admit it's slightly redundant because here we Define what this structure is supposed to look like so this might not be the most beautiful example but it is about all I have in the example project we've been building so we're just gonna go with it and you can choose to do this or you can choose not to do this that's the thing with typescript is if there are certain areas where you don't feel it's going to provide value you don't have to Define all the extra types however the more you define the more static benefits you're going to get so basically we're going to describe what the interface for a customer is it's going to be very similar to what we have down here so name is string and notice a key difference here this is lowercase and this is uppercase this is a typescript type so we'll continue from this and say industry also of type string and then orders is going to be an array with an object and inside of this object we'll have a description of type string and amount in sense of type number and we'll just add a semicolon there at the end now you could describe what an order looks like if you wished separately so let's just say I order and this is going to be an object and we'll just copy what we have down there up here description is of type string and the amount incense cannot type today is of type number and now what we can do is instead of having this structure down here what we could do is we can just say orders is and I order array and go ahead and add a semicolon there ah just a small typo there you're not supposed to have the equal sign all right so now we have an array of this interface type I order I is basically just a way to say that it's an interface I'm not wildly a fan of putting the type in the name but I already started so we'll just go with that it's not a big deal if you just want to drop those that's fine but I already had customer with a Capital C down here so I just decided I would stick with what I had here now you say new schema you can inside of angle brackets and this is known as a generic say what type it is so you can say I customer now if you want to say something is optional in the interface you can do that with a question mark here so that can be optional the orders can be optional and let's just say the industry can be optional now if you wanted to encode manually create a user it might look something like this cons C is a new customer passing in some values just as you normally would so name can be test industry can be test and if you wanted to get that typing of this and you want to be explicit about it what you can do is say what type the const is with a colon and this is actually going to return an existing type that you can read about in the Mongoose docs which is a hydrated document so it has values and then generic typed to whatever that interface is in our case I customer and we'll see if this is on the right track the hydrated document is going to need imported so in this list here we can add hydrated document and there we go zero errors and now you should be able to say something like console log C dot name and you will see that over here in the running application if you tried to do something like invoke a method such as C dot name with parentheses and that's actually a bad example because I think that's a key word so let's just do c Dot N property end does not exist on type document and then you can see I customer right there in its type so those are some of the basics of bringing typescript into your code for Mongoose I have a lot more typescript content in my react Series so definitely check that out if you want more information just having typescript installed is probably going to help with a lot of common problems and that is because typescript can often infer the type based on what you are assigning some constant or variable so if I say let X be 5 it's smart enough to look at the assignment and be like oh that's a number let's type X to a number rather than just give it type any this means you will often get a lot of benefit from typescript even if you're not explicit in every single thing you do but sometimes being explicit is nice helps you prevent mistakes and be very clear in your code what you're trying to do but it can lead to some code bloat so just kind of be aware that you know if you have interfaces that describe these things that describe these things and then you got like three layers of the same thing and sometimes all that extra stuff doesn't really make code simpler so keep it lean uh yeah that's all I got for you stay tuned for the next episode peace out what's going on everybody Welcome to episode 30 in your node.js Series this video is really just going to be a conclusion and some final thoughts some suggestions on what to study next first I wanted to congratulate you on making it this far in the series honestly didn't think you would make it this far so pretty good job the first thing I wanted to talk about is what we did not cover which is obviously unlimited information but these are some things you might want to study more the biggest one that comes to my mind is authorization we didn't talk about anything with that so definitely do some extra research and I would recommend learning about Json web tokens as well as cookies and local storage and all the differences between all of these things now really you could probably just look up auth with node.js there's tons of good resources out there web dev simplified the net ninja fireship obviously these are all really good one channel that I really like is Dave gray so really good detailed information on authentication inside of node.js so highly recommend it next up deploying we didn't talk about in this series but I did do a video on node.js deployment to AWS so you can search node.js to AWS and boom right there it is I also did a video deploying next.js to Versailles which is going to be pretty similar which brings up an interesting topic I'd highly recommend learning about next JS it's going to give you an environment where you can execute backend code and statically generate your site so very similar to node.js because it's going to be back-end code it's going to be JavaScript but slightly different so definitely check that out it's part of my react series that I've been pushing this whole series just because there's so many good resources in that Series so you can find that in my react.js full course this is part one of two I should have part two coming out in the next few days pretty sad view count pretty disappointed but the content is pretty good so definitely check it out next up databases we talked about mongodb here but obviously there's so much more you can learn about relational databases or other nosql databases potentially something like dynamodb or you could learn about in-memory caching with something like redis lots of cool stuff there so if you're looking for someone else to study that's what I'd recommend and if any of this interests you and you think a second part of the series would be good drop a comment down below let me know what you would like to see what you'd like to see changed and so forth next up is paging for an API so if you have a Million results how do you send those in Pages learn a little bit about that and of course security you can never study too much security which we only touched on possibly zero in this series except cores for a little bit and I basically just said hey let's disable it so not really great security course here but you should spend some time doing that before you deploy an application for production another very interesting thing that would be good to learn would be graphql this is basically a different way to create an API where you can customize the query from the front end and get exactly what you want from the back end we talk about how to do that in react with the back end being Django in my react series but you could of course create a node.js graphql backend and connect to that from react stay tuned for upcoming content on this series if you want to see more web development I'd love to do some also considering some other topics so let me know what you'd be interested in seeing in the comments section and I will see you all in the next series peace out
Info
Channel: Caleb Curry
Views: 37,334
Rating: undefined out of 5
Keywords: python, tutorial series, tutorial, programming, code, coding, caleb, curry, intermediate python, intermediate, how to
Id: pkg0J6lpKT4
Channel Id: undefined
Length: 222min 48sec (13368 seconds)
Published: Wed Feb 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.