How to Use the MEAN Stack: Build a Web Application From Scratch

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video you're going to learn what the mean stack is we're going to set up a new project build out the back end and the front end and connect to mongodb if you want to follow along there is a written version of this tutorial and the full code is available on GitHub there's a link in the video description so what is the mean stack well stack refers to a combination of Technologies the mean stack consists of mongodb Express angular and node.js and there are other similar variations like the M Stack which swaps out angular for react now in the mean stack we use mongodb to create the database layer node.js and express to make up the middle or application layer and angular to implement the presentation layer in this mean stack tutorial we're going to utilize these four Technologies to develop a basic application that's able to record the information of employees and then display it using an angular front end we'll Implement all of the basic crud operations create read update and delete we'll be able to view all employees add new employees update existing employees and delete existing employees so to get started we're going to use node.js version 20 plus and a code editor for this I'll be using visual studio code and these are both free downloads along with that you'll also need a free mongodb Atlas cluster Atlas is our cloud-based database service our free tier cluster never expires and doesn't require a credit card if you don't already have your cluster set up up we have a video to guide you through that as well so pause this video go watch that one and then come back here when you're done now the mean stack lets us create a full stack solution and for this project we're going to create both the back end and the front end the front end we're going to implement using angular and the back end we're going to implement using mongodb node.js and express and so we're going to call the front end client and the backend server I'm going to use shell commands to create directories and files but you can use any method that suits you first I'm going to create a new directory called mean stack example and then I'll move into that directory within that directory I'll make another directory called server and make another directory in that directory called Source SRC now I'll move into the server directory and then I'll run npm and nit to initialize a package Json so now if we look at our directory structure we have the meanstack example we have server within that source folder and our package Json next we'll install our dependencies we'll install cores EMV Express and mongodb now since angular uses typescript let's go ahead and use typescript as the backend as well so we'll install typescript along with the types needed as Dev dependencies now let's create a few files we're going to create a TS config file and a EnV file for our environment variables next we're going to CD into our source directory and create create a database. TS file an employeer routes. TS file employee. TS and server. TS now we see in our folder structure we have our package Json TS config our EnV file and then under Source we have our database our employee routes employee and server let's first go into our TS config file and we'll paste in our configuration so our basic configuration we're monitoring our source directory and everything within that and our output is going to be in disc we're using commonjs and Es 2016 very standard stuff for typescript so save that and close it and next we'll work on our employee interface so if we go over here to employee. TS and I'll paste this in so we're going to import mongodb and we're going to create our employee interface so all of our employees should have a name which is a string position which is a string level which could be junior mid or senior and optionally it will have an underscore ID D field which is a mongodb object ID this is optional because it's generated by mongodb so when we create a new employee we won't initially have this field but when we retrieve an employee from the database it will have the field we can see that this is optional from the question mark here so go ahead and save that and close it next we'll work on the database. TS file so in here we're going to again use mongodb and then we're going to bring in that employee interface that we just created we'll export our collections which could have employees which are of a Tobe collection type employee we have our connect to database function which will accept a urri string in here we'll create our Monga to be client using that URI and we'll connect to our client this is an async O8 function so we're awaiting that connection and then we're going to get our database which is mean stack example now if this database is not already in our cluster it will automatically be created for us now next we're going to apply schema validation now this is going to ensure that all of our documents follow the shape of our employee interface let's see how this works below here we have our apply schema validation function which accepts our database and here we're using a Json schema if you want to learn more about Json schema validation there's a link in the video description but this is going to apply this schema validation onto our database so this is going to make sure that this is of type object the required fields are name position and level and the following properties could be there underscore ID name position and level now this validation is done at the database level and this is good practice to ensure that we don't accidentally store data that doesn't match the shape of our model so after that going back up here we're creating an employees collection which is going to be on our database and then the collection is called employees now again if we don't already have this collection it's going to create it for us next we'll add that to our collection. employees we'll make that equal to employees collection again that's what we're exporting up here at the top we're exporting our collections so we'll go ahead and save that and close it next let's open up ourv file and we need to Define our Atlas URI so yours is going to look similar but a little bit different than this one now in here you'll specify your username and your password and then your cluster you can get your connection string from the atlas UI and here's what that looks like under database you can go to connect and then drivers and this is my connection string again we have to put in your username and password now be sure to save that file and then we're going to move on to the server. TS file here we're going to use the EnV package so that we can read our environment variables we're going to use express and cores and then use that connect to database function that we created in our database. TS file so here we're loading our environment variables by running the EnV config next we're getting our Atlas URI environment variable if we don't have the atlas URI defined then we'll console error and message and then exit the application next we're going to run connect to database pass in our Atlas URI and after that we're going to start up our express application we're going to use cores and then tell it to listen on Port 5200 and then we can console log that the server is running on that Local Host port and of course if there is an error we'll catch that and then console error that error go ahead and save that and then close this file all right now we should be able to run this and make sure it works so for this we're going to use TS node we'll run npx TS node and then that server. TS file in our source directory if all goes well you should see Server running on Local Host 5200 okay great job next we're going to build the restful API we're going to implement get post put and delete endpoints for our employees so we're going to do that in our employees. route. TS file and to get us started we're going to import Express the object ID from mongodb and our collections from our database file we're going to implement a employee router which is going to be an Express router and we're going to tell it to use Json our first route is going to be to slash and it will be a get request we're going to make this async and then surround everything in a tri catch of course and then first we're going to await our collection employees. find and turn that into an array so theind with empty curly braces is going to find everything so this is going to get all employees from our database if all goes well we'll send a status of 200 and send the employees back to the front end now notice these question mark symbols here these are optional chaining operators this enables us to read the the value of a nested property without throwing an error if the property doesn't exist if it doesn't exist it will just return undefined this is going to help us to keep typescript happy and if something isn't there it will just return undefined after this we'll have another get endpoint this is going to be to slon ID this will allow us to get an individual record so the ID here can be passed as pams into our function so we're going to get that ID here from our request ps. ID again if it's not there we'll use optional chaining to turn it into undefined then we'll Define our query here which is going to look for the underscore ID that equals the ID that we passed through our prams and then finally our employee is going to AWA our collections. employee. find one and pass in that query so it's going to find one employee so if we have an employee then we'll return a status of 200 and send that employee back to the front end otherwise we'll send a 404 and say that we failed to find the employee with that specific ID and if anything else happens we'll catch it in our try catch here we'll return a 404 and say fail to find the employee right after this we'll Define our post route which is going to allow us to save a new employee so post is going to be to slash our employee is going to be passed to this endpoint through the request. body so we'll await collections. employees. insert one and insert the employee that was passed to us so the results will be here if acknowledged is true we'll return a status of 2011 and we'll say that we created the employee otherwise we'll send a status of 500 failed to create a new employee and of course we have a try catch for everything and if another error occurs we'll return that error all right after that we have our update Route which is going to be a put to a slash ID so this will update an individual record so again we're going to get that ID from our prams we'll get the new information from our request. body we'll create our query which is going to select that specific ID and then our results are going to be collections. employees. update one we'll pass in our query to identify that one object ID and then we'll pass in our new object so we're going to say set employee so this will update all of the existing employee Fields with the fields that we passed to this endpoint so if we have a result and a result matched count then we'll return a status of 200 and send the updated an employee message else if we don't have a result matched count which means we didn't match anything then we'll send a 404 failed to find the employee and if anything else happens we'll just send a status of 304 failed to update the employee and of course again surrounding everything in a tri catch and we'll just return unknown error if that happens and then our last route will be our delete route so we have our delete to/ ID again picking a single ID here we're going to get that from our pams our query is going to identify that one document with that ID and then we'll call collections. employees. delete one pass in our query and we have our results here so if we have results and the deleted count then we'll return a status of 202 and we'll say removed an employee if we don't have a result we'll send a 400 failed to remove an employee if we don't have a deleted account at 404 failed to find an employee and again try catch with an unknown error if anything else happens so let's go ahead and save this file and close it now next we need to instruct the express server to use the routes that we've defined so back in our server. TS file at the top let's go ahead and import our employee router and then right before the app. listen let's say app.use SL employees employee router so here we're telling it the slm employees path should use this employee router and would be the root of this employee router so let's save that and then we do need to restart our server so contrl C and let's run this again awesome so that's it for the server next let's build our angular web application to interact with it now to build out our angular web application we're going to use the angular CLI to scaffold the application first let's open up a new terminal we need to keep our server running in this terminal and let's go ahead and open up a new one if you don't already have the angular CLI installed run this command npm install DG at angular CLI this will install the angular CLI globally now I need to make sure that I'm in the meanstack example folder so I'm going to CD into that and then I'm going to run this command ing new client-- inline template D- inline style D- minimal D- routing D- style equals CSS so what this is going to do is going to create a new client directory and install our angular application in this directory the inline template and inline style is telling it that we want to keep everything in one file instead of creating a separate HTML file and a separate CSS file the minimal flag is going to tell it to skip any test configuration since we're not going to cover testing in this tutorial let's just keep it minimal the routing flag will generate a routing module and the style equals CSS just means that we want to use CSS so let's run that now depending on what type of application You're Building you may or may not want to enable SSR and SSG so that's up to you now installing these dependencies might take a while I'll go ahead and speed this up all right next let's navigate into our client directory and then just to make sure it's all working we can say NG serve - O the- O is just going to automatically open this in our browser and there we go it's working and it's running on Local Host Port 4200 the last thing that we're going to install before we start building out the application is angular material so we have our server running and we have our client running let's open up another terminal and let's CD into our mean stack example and client directory next we're going to ngad at angular slm material it's going to install that package we'll say yes and so this is going to allow us to use angular material for our styling and you can select any color theme that you want whe whether you want to use the angular material uh typography Styles and if you want to enable angular animations nice so now we're ready to start building out our application the next thing that we'll do is we'll create our employee interface on the client side now the angular CLI makes this super easy we can run this command NG generate interface employee and watch what happens it created this employee. TS file for us so if we navigate over here to client and then Source app and now we have this employee. TS file with an interface that's ready for us to Define so just like we did on the server side we'll Define the name position level and then the optional ID let's go ahead and save that next we're going to create an employee service angular recommends separating your business logic from your presentation logic so that's why we're going to create a service that handles all of the communication with our employee endpoint uh of the API this service will be used by all of the components within our application so again we're going to use the angular C and we're going to run NG generate Service employee so now it's created this employee service and it has scaffolded that out for us so I'm going to replace this scaffold and we'll go over this code so from angular core we're going to use injectable and Signal now signals is the new way of doing things and if you want to learn more about signals there's a link in the video description we're going to use the HTTP client from angular common HTTP and then our employee interface that we just created now injectable defines where this is going to be used and this is going to be used in our route and then we have our employee service class within this class we have our URL so right now we're uh in local development so we're using Local Host 5200 for our server and then we're going to create a couple of signal that we can access within this class so employees and employee in our Constructor we're going to use our HTTP client and then we have a private function here that refreshes our employees so this is going to uh use HTTP client to get and then at the URL SL employees remember on our server SL employees is going to get all of our employees and we'll go ahead and subscribe to this and set our employees so that's going to set set this variable up here employees and then we have a public function here that is going to get employees which is going to run that refresh and then return employees next we'll Define get employee this is going to get a single employee so we have an ID here again this is going to use HTTP client and then the URL employees but defining an ID so remember on our server that's going to return an individual employee we'll subscribe to this and we'll set our employee here and then return it we have another uh function here that creates an employee so we pass in our employee to this function again it uses our HTTP client to post to our slm employees route we pass it the employee and response type is text we have our update Route and our delete route just like the others so again we're defining this service to keep all of our logic separate so go ahead and save this and close it next we're going to make some changes to our app.config let's go ahead and open this we need to add to this our provide HTTP client and with fetch this is going to enable the HTTP client within our application we already have our uh standard providers here but we need to add our HTTP client provider as well so here we're adding our provide HTTP client and we're ALS Al passing in with fetch so that we use the standard fetch API and we'll save that and close that and now we can start generating our components in angular a component is a reusable piece of code that can be used to display a view so back in our terminal again we're going to use the angular CLI we'll say NG generate component and the component name is going to be employees Das list so that creates a folder here employees list under app within that we have our employees list component.ts and we have a basic scaffold here that we're going to replace so let's walk through this from angular core we're using component on anit and writable signal we're pulling in our employee interface our Employee Service our router module and then some material components so we have our material table our our button and our card and of course we're going to use all of these in our Imports here to make sure that they're usable we have some basic styles that I've added here to make the table width 100% and then uh the first of type button will add a little bit of margin to the right so just some basic Styles here the rest of it is taken care of by angular material so here is our template our markup so again instead of having separate files for these which is totally possible we're going to include our styles and our HTML markup right here in this one component file so we have a card here in our template is the first thing we have our header employees list and then we have our card content within the card content we have a table and this is a cool thing that angular material helps us with we give it a data source our data source is employees this is our employees signal that we created in our employee service so next we're going to Define our columns we have a name a position a level and an action column and then the contents of those so we have our element name which is coming from employees here we have our element position our element level and then the last column is our action column this is where we're going to have a couple of buttons we're going to have an edit button and a delete button the edit button is going to use router link and send us to edit slash and then we're defining the element ID so this going to allow us to include that element's information on this route and then delete we're going to have a click here which is going to call delete employee passing in that element ID so really basic setup and then at the end here we're defining our header row and the rest of our regular rows at the bottom of our card we have our card actions we have one last button that is add a new employee and again we're going to use the router link to send us to the new route so Slash new all right after that we have our employee list component class which implements on a nit we're creating our employees variable initially it's blank as a writable signal we're defining our displayed columns this is for us to pass into angular material to tell it which columns we want to display in our Constructor we have our employees service on a nit we're going to fetch employees so let's look at that is down here private fetch employees so this. employees is going to equal this. employees service. employees so again we're pulling for from our employees service our employees variable and we're calling our employees service get employees so this is going to tell it to go ahead and fetch all of our employees we have our delete employee function here which is called from our delete button up above and this is going to again use our employees service and call the delete employee function adding in the ID we're going to subscribe to that and then after that we're going to fetch our employees again to make sure we get the updated data all right so that's the entire list let's save that and go ahead and close that now before we go look at this we do need to add a couple of things here we're going to go to our app. routes. TS and we need to Define our routes first let's pull in our employee list component that we just created and we have no routes currently so let's add in a new route so the path is going to be blank which is our root path we're going to tell it to display that component at this path and this is an optional title we'll say it the title of this path is employees list so let's save that and close that file and then we'll go to our app. component.ts we're going to import our employee list component here and a material toolbar module we need to add that to our Imports we're going to include some basic Styles here and let's replace this template so we'll have our toolbar which is going to say employees management system and then under our main we're going to have our router Outlet now the router Outlet is going to display whatever the route has sent it so let's save that close it and now if we go back to our browser we should see something we have our employees management system toolbar at the top and then we have our card with a table and a blank table of course because we don't have any data in it yet we have our add a new employee button but that doesn't work yet but we're getting somewhere let's move on now to the next step all right next let's create a page for adding employees so we're going to need a form to fill out the name position and level to create that new employee and then for editing employees we're going to need a similar form so first let's create the employee form so again we're going to use the angular CLI NG GC employee form so the G is shorthand for generate C is shorthand for components so we're going to generate a new component called employee Das form so it's added that here employee form and employee form component we're going to replace this basic scaffold and let's go over it so we have a component effect event emitter input and output from angular core then we have our form Builder validator and reactive form module from forms we have some material modules our input our form field radio button regular button and of course we need our employee interface we're going to make sure that we import all the modules that we need here we have some very basic Styles going on here and then our template we have starting out with our form form group is going to be called employee form and then for our submit we have our submit form function which we'll look at in just a minute our first for field is our name and then we have have some validation going on here so a if is the angular way of saying if name. invalid so if that's true then we're going to display this error the name must be at least three characters long our next form field is our position so in here we're going to do another validation here and say the position needs to be at least five characters long and this is also set as required as well as the name input is set as required as well next we have our radio group so we have our options of Junior mid and Senior and then we have our button to add the employee we're going to disable this button if the employee form is invalid and then let's look at our class our employee form component class uh we're going to have an initial state so again this form is going to be reused whether we're updating or adding a new employee so we could have an initial state if an employee exists we're going to create an output for our form values changed so if the if they've changed we're going to emit an event and the same thing as the form is submitted will emit an event we'll Define our employee form here is this. formbuilder dog group so we're grouping these inputs as our employee form so we have our name the initial value is blank and then we have our validators here it is required and the minimum length is three same for the position the initial value is blank it's required the minimum length is five and then the initial level will be junior and it is required for our Constructor we have our form Builder and we're going to have an effect here since we're using signals so the employee form. set value is going to be set every time an effect is run so the name is going to equal the initial state. name or blank if there is no initial State position same thing position or blank link and then level the initial state or Junior next we're going to get our name position and level that is going to be from our employee form. getet name the position and the level this is going to allow us to use these in our template lastly we have our submit form so when the form is submitted uh we're going to emit this. employee form. value as employee so the value of all of our inputs within our employee form will then be mitted all right let's save that and close it and then back in our terminal let's create our ad employee component so again we're going to NG generate a component called add employee so here we have our ad employee and let's replace this scaffold and here we have our component our router our employee form component that we just created our employee interface our employee service and our angular material card module so we'll use our employee form component and our card module here as Imports and here is our template pretty basic we have our card our card header is add a new employee and then our card content is going to be our employee form app- employee dform is that form component that we just created now form submitted when that is run we're going to run ad employee with the event that we receive so here's what that looks like in our class our ad employee component class we have our Constructor which we have our router and our employee service that we're using and here is our add employee function so it accepts the employee which is going to be the values that we get from that form and then we're going to run Employee Service remember our service that we created we're going to run the create employee function within that and pass it our employee we'll subscribe to that and then next we'll navigate to slash so after it's been created we'll navigate back to the list if there's an error we'll alert that and console error the error and then lastly we're going to run get employees from our Employee Service to refresh our employees well let's save that and close it and then back in our terminal we're going to create our edit employee component so there that is let's open it up close the terminal and we'll replace the contents there this time we're using component on a knit and writeable signal from angular core we have our employee form again from the router we're going to use activated route and router we have our employee interface our employee service and our card module from angular material all right we'll make sure that we import our form component and our card module and then here's our template again we have a card a header of edit an employee our content is going to be our employee form and then the initial State here we're passing in our employees signal we'll get that a little bit below here and then on form submitted we're going to call edit employee with that event so let's take a look at the code for that so our edit employee component class implements on a nit we're going to Define employee as a blank object at first as a writable signal in our Constructor we have our router our route and our employee service now on a nit we're going to get our ID from our parameters if we don't have an ID we'll alert that there's no ID provided and then we're going to get our employee we're going to use that Employee Service to get the employee uh using that ID and then we're going to say this. employee equals this. service. employee so now the employee up here has a record if the ID was found so then again we call our edit employee function which accepts those updated parameters from the form so this. employees service. update employee we call that function passing in this. employee which is a signal because it's a signal we have to call it uh we so we're passing in the ID from that signal or blank and then we're passing it the updated values contained in our employee object we'll subscribe to that once it's done uh we're going to navigate back to the rout and if there's an error of course we'll console error that so let's save and close that the final thing that we need to do is go into our app. routes. TS file and we need to import our new components our add employee component and our edit employee component and then we'll add in two more paths here's our root path then we'll have A New Path which is SL new and for that path we want to display add the add employees component We'll add a path that is edit slth ID and for that we'll display the edit employee component so let's save that and close it let's go ahead and test it out we shouldn't have to restart anything just go back to the browser and let's try it out add a new employee say Jesse Hall position is developer Advocate we'll say mid and add and there we go we can edit it let's change it to senior add and now it's senior and if I delete it it should delete awesome congratulations on building your first mean stack application now for more ideas and advanced concepts go to our developer Center there's a link in the video description and if you have any questions go to our community forums again there's a link in the video description now if this video was helpful give it a like And subscribe for more mongodb content
Info
Channel: MongoDB
Views: 843
Rating: undefined out of 5
Keywords: MongoDB Atlas, TypeScript, Angular, MEAN Stack, Developer, Introductory, DA, VI
Id: GcYxQ0A7tVM
Channel Id: undefined
Length: 34min 49sec (2089 seconds)
Published: Thu Mar 21 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.