hey everyone welcome to this video so in this video as you can see we are going to cover each and everything that you need to know to start your node journey as a beginner now before you skip this video I'll highly recommend and request to watch this video for at least 5 minutes and then you'll understand that quite a few things we are going to cover and also one more thing I want to mention and that is I've given lot of effort so please like and comment because it's very very important and also the next 24 hours also will be very important so please share with your friends also I'm targeting at least 500 likes and 100 comments in next uh 24 hours and also the total like uh Target for this particular video will be 15,000 all right so let's see what are the things that we are going to cover so first we'll start with nodejs Basics and let's see the chapters that what will be under this particular section so we'll start with installing nodejs how you can run JavaScript with nodejs what is the node module system what is module exports and require and also we are going to explore the module rapper function then we'll move to the second
section which will be npm and the package management so let's see that so we are going to see what actually npm is what is package.json how you can create package.json and how you can manage dependencies right how to add and remove dependencies and what is the difference between de dependencies and the normal dependencies now next we are going to cover code modules and asynchronous programming now here we will cover some of the modes modules so very very important path module what is file system HTTP module callbacks callback H what is promises how you can create and consume promises how to do error handling with promises what is Asing function what is aate keyword and also how you can do error handling with try catch next we'll move to event driv programming so here we are going to see how you can uh what is actually event Emer class and how you can create and consume your own custom events next we'll move to very very important Express JS fundamentals so let's see
what are the things we are going to learn here so first we'll understand what is Express JS how to install Express JS how you can create basic Express server what is the app object how you can Implement routing route parameters what is Route handlers middleware the concept of controllers how you can create middleware and also how we are going to also we going to understand that how you can create customer middleware next we'll move to template engines and Crow operations so here we are going to start with ejs which is one of the most popular template engines that we will cover here how you can set it up with Express right how to create and render EGS templates and then we'll move to crowd operation with HTTP modules after that we are going to install Postman and also we'll understand how we can use Postman to test our API request next uh we'll start with another very very important sex and which will be database integration and the rest full AP development so here we are going to learn what is mongodb what is the basics of mongus how you can create restful API so here we are
going to create this bookstore project and then we'll start with extremely important section which will be authentication and the authorization or role based authentication so here we'll be covering first basic two how to two routes we how to create registration endpoint and also how to create login logic and after that we'll be moving to security and advant features so here we are going to cover quite a few things so first what is big gript how you can has password how to compare passwords what is the concept of JWT how you can create and sign JWT how to verify JWT how you can create middleware for JWT verification how to protect routes or how to implement role based authentication how to do file upload using multer and cloudinary and react how to fet uploaded images although we are not going to cover any UI but I will give you some ideas how to implement change password functionality implementing sorting pag and also how to update fet images right that what are the images that we are going to upload to cloud inary and also you're going to understand how at I
already mentioned that will be implementing Ro base authentication so how to implement image delete functionality for admins after this we'll move to the Advan mongodb section so where we'll be understanding this aggregation Concepts so what is aggregation pipeline uh how to use common aggregation operators how to do complex data transformation and also how we can use this lookup for joining collection then we'll move to another very important section which will be deployment so we going to understand that how you can prepare node application for production how to set it up uh the environment variable and the configuration and then we are going to understand how to deploy in render and also how to deploy on versel next we'll move to nodejs with graphql so here we are going to understand very basically LEL of graphql concept so we'll uh see introduction to graphql how to set graphql server with app and how to define your graph Quil schemas resolvers how to query and muted data with graph Quil and at the end we're going to create a project where we are going to integrate graph kill with mongod via
mongus and at the end we'll finish with another very basic level of chapter which will be how to use typescript with nodejs so here also we going to uh see that how you can set typescript pro uh with nodejs project how to configure this TS config files some of the basic concept of Tes script in nodejs development how to work with modules and then we are going to understand some of the very basic level of Express do Express uses with typescript and also how we can create models using mongus so these all the things we're going to cover in this particular video and I'm pretty sure that you'll be learning lot of things this video will be actually really based if you don't have any idea on noj but there are some prerequisites so first you need to know some very basic level of HTML you need to know good amount of JavaScript and also if you know like very basic level of typescript that also will be really good so that's all so now uh again I'm repeating so if you like this video please give a like comment down subscribe to my channel and also share
this video with your friends so let's get started and good luck all right everyone so first we'll start with installing and downloading noes so first what you can do right just come to the official website of nodejs and here you'll get the download option and it's very very simple so there are multiple ways you can install so either you can run in your power cell and then you can install using this command or else you can directly go to the pre-build installer select the operating system that you're having download it and then simply install it just like other software now once the installation is completed just go to command line and search uh for here let's do it node and hyphen V which will give you the node version and if you're getting the node version that means your node is properly installed right now once this is done now we'll start with our first chapter which will be the nodejs basics so here we'll start with how we can write our JavaScript with uh noj so let's start uh learning all the things step by step from the next section all right every so let's get started so as this video will
be for complete beginner so whatever things that we are going to learn in this particular one we will be learning from completely scratch so the that is the reason I want to mention one thing that if you already know some of the things then you can directly go to a particular section as I already I will add time stem in the description so first thing we are going to start with uh node just Journey with writing our first hello world code in node okay see when we are talking about writing node J we can U write node J in mainly two ways the first one is called node J Ripple which called the read EV print Loop and then we can directly write noj in a Javascript file so to write uh nodejs code so first thing what we need to do and before that I want to mention you can see that I already created a blank folder I don't have anything else here and we are going to learn each and everything so first I'm going to create a folder here right so let's give this one as I will give hello world node okay and now to write nodejs code using Ripple what we need to do right first we need to open our command line
so I'm going to open and here first obviously you need to install node there has to be node install in your machine or else it will not work and then what we need to do we need to type node and then just press enter now here you can see that you will be getting uh this kind of thing and here you can write whatever you want to write for example I want to do a console you can see that you are getting the reference also and I will do console log of hello nodejs hit enter and you can see that you are getting the output you can do anything you want now let's say let's do 2 + 2 4 2 - 2 0 if I do 0 divided by 0 you can see not a number if I do 100 divided by 0 you can see we are getting Infinity so everything you can do here right and now the main thing is that why we then not write in this way obviously this is just to give you a basic example when you will be working on a very complex application this is not the way you will write code right now to exit
from this what you need to do you need to press contrl C sorry I pressed two times so you need to press contrl C and then you'll be able to exit or you can do this contr D or also you can type do exit Okay so this is very basic way of writing nodejs in your terminal now let's start with our writing our first nodejs code so inside this folder I'm going to create let's create index.
js now again I want to mention one thing is that each and every sorry I think I uh create it outside of it let me just delete it so I'm going to create it inside this folder and I will give this one as index.js so what I was mentioning is that whatever files that I'll be creating inside a folder right I'll be giving the name as index and if you notice my previous videos also I follow this structure now some of you actually mention that why I always give index.
js the reason is because you can see that I given a proper folder name so if I'm giving already a proper folder name so there is no point of again writing hello world .js right until unless you are having multiple files inside of it and the main reason of writing index.js is that this indicates that this is the root file of this particular folder okay so now here so this will be a simple JavaScript code whatever you are going to write inside of this as you can see that the extension is actually a JavaScript so I'll do a console.log and again I'm going to do a Hello nodejs save it now the point is that because here we need to run this file right and to run this file we need to go to this folder in our terminal so let's click on this folder and let's do a open an integrated terminal so I'm going to click here so here what you need to do you need to give node and then you need to give the file name so inside this we have index.js I'm going to write index.js enter so you're getting hello nodejs if I just change this one so I'll
do hello JS save it and then run it again we'll be getting hello JS now again as I already mened and that you will be able to do anything you want here for example let's say I'll take some array right so Lon array and this will be 1A 2 comma 3 comma 4 okay and let's log this array so I log this array and I'll give a comment array Also let's do one more thing is like for example we'll give a set time out here and I'm going to give a delay of let's keep two seconds and I'm going to log here so let's log something like that this message is delayed by 2 seconds now if you are watching this video for the first time or you don't have any ID don't node I highly recommend don't skip any of the things like all the things are related I created this video in such a way that each and every lecture will be interconnected with each other and if you're completing this course you no need to buy any premium course or anything that much guarantee I can give
you save it and now after this I'm going to log one more thing and give this one as this is the okay let's give this is the last line of the synchronous code so I'll give sync code for sort and now I'm going to just do let's expand this one let's clear it and again I'm going to do node and then we'll do index dot sorry do JS so I'm running this particular file right index.
js hit enter and let's see what is happening see this actually wait until unless this set timeout is getting run right so first time you're getting this last line of the sync code and then after 2 seconds you're getting that this message is delayed by 2 seconds now actually this is not the point the main point is that how you're going to write your fast nodejs code and how you're going to run that file so what we have learned so far is that there are two ways we can do that either you can run opening your terminal that is the basic way obviously that is just for giving you the example and the second is how we are going to write a normal nodejs code so here we need to create a file and then we'll type node and then we'll give the file name and then we'll be getting the results now for example here I'm going to do something like uh let's do a sum dot JS okay and I'm going to create a function we'll do function sum so we'll do num 1 comma num 2 and I'm going to Simply return num 1 + num 2 and I'm going to do a log and I'll do
a sum of 2 comma 3 save it now again as I already mentioned so I just want to show you that that is the difference that how you are going to run the file so now instead of doing node. index.js I'm going to do node of sum. JS hit enter so you're getting five here right so this is the result so this is very the basic way of learning or writing your node J or hello world node now let's move on to the next topic which will be we are going to learn the node module system all right so next we are going to learn what what is node just module system what is the uses of module. exports what is the uses of require and then also we going to learn some of the other very basic things okay now what exactly node module system see node by definition node module system allow you to organize your code into multiple reusable pieces of code as simple as that see for example you are creating a very large let's see Commerce application right where you'll be having different different section something like that now if if you're writing the each and every line of code in a single
file what will happen that code will be very messy and that is also not recommended and you will not be able to manage that code properly so what will happen nodejs has a module system where you will be able to create different different modules and then you can use those modules in a single root module if you have worked with react right so just like react has a root component and then you'll be having multiple components like child components and what at the end you will do you'll import those child components into your app.js and at the end that app.js or the single page is getting rendered so this is similarly the same similar kind of concept you can understand so you let's say you have a module one and then you have a module two and let's say you have a module three now at the end what you'll do right you'll use those all modules in a root file and at the end your root file will be getting rendered right so by definition again I'm repeating because for beginners these kind of uh things be also getting asked in interview that what is node just module system see node just module system allows you to
organize your code to multiple reusable pieces of modules right so you'll be creating multiple modules and then each file each file again I'm repeating each file in nodejs will be treated as a separate modu okay so let's see how we are going to do that now uh let's go here and I'm going to create one more and I'll give two space and I'll do node module system now again all the things that we are going to learn in the first couple of hours right see these might seems not that much important but believe me these all are the basic Foundation that you should know without this you'll not be able to create very complex on so that is the reason I'm giving very simple example or some Theory so that whenever you'll be creating some complex thing and Learning Express it will be easy for you to understand all this and here let's again I'm going to create index.js now again index.js is a root file okay root file inside this folder I'm talking about these two folder now again I already mentioned that this has
two main thing you need to understand what is called module. exports and then you have reord now if you talk about right so this is similar to what you you have like we have uh export right and this is similar to you have import so you are exporting something in one file and that thing you want to use in a different file right so similarly you can also use export and import but for now we'll just keep it like this we use module.
exports and reir and these all are coming from common J so node just actually use common J module if you want to learn more you can go to the documentation also right so see what exactly module. export does so module. exports is used to expose functionality from a module similarly require is used to import functionality from other modules as simple as that right so whenever you need to require a particular module you get whatever was assigned to module.
exports in that particular module so let's see so I'm going to create our first module and let's give this one name as first module. JS and in this first module uh let's create some very basic functions okay so I'm going to create add function once again and I'll give a comma B and let's return a + b okay next uh let's create a substract so do substract and I'll do again a comma B and then I'm going to do return a minus B and at the end we'll create one more very interesting thing and that is function I will do a divide method and I'll take two number again so do a comma B and I'll check here that if B is equal to equal to zero so we are going to throw so to throw a new error we need to use this new keyword and this will be error Constructor and I'm going to give error that divide by zero is not allowed
okay and then here we are going to return what will return a divided by B because at the end we are doing the divide and now what my task is I need to use all of this method in this index.js which is my root file inside this folder so how I'm going to get cre it here right so I need to export it somewhere so that I'll be able to import it in this file and to export it we need to use this module so again I already mentioned right so this will be a module so L module.
exports sorry L module do exports and this will be so here we are going to pass the add then we'll pass the substract and then we are going to pass the Divide save it so now let's go here and then I need to get it in this component correct so now I'm going to give a name right let's give const first module and this will be require right so we need to use this require which will be require keyword so that means you're telling that I require something and I need from this first module so you need to go to that path so I'll go to First module okay and if you over right you'll be getting this uh if I over here you'll be getting this is a common just module it may be converted to a es module so to do this one we need to change something in the package. Js and other things but that is not very much important here the main thing at the end the concept is same so it is like they're telling that you need to use this import this so import a from this file so this is similar to what we are doing here right
we are doing require so now what we doing that we now we require this module and I need to trigger something here so what we can do simply we do log and I'll do write first module dot you can see that we are getting all this function because now this is now accessible so I'll do add and then this add will take two things right so we'll take the first and so I'll give it 10 and 20 and now let's save it and now let's go here again to run this right we need to go to this folder so I'll go to this folder I'll open in the terminal and then I'm going to first close all these other things so we have a module system and again we need to run node space okay I don't know why this comes always let me just clear it first I'll do no mode and then do index.js hit enter so we getting 30 so you can see that we're getting 30 because this method is getting triggered now let's say if you notice right in this divide method we are throwing a error and somehow I need to log this error so how we are going to do that so
to do this one right let's go here okay first I'll just minimize this one let's create a very try and catch block now these all are also very basic JavaScript concept so we will take a try catch and catch will give us error right here so in the try what I will do so I log here that okay trying to divide by zero and then here I'm going to do let result will be so I'll call that first module dot we have divide and I'm going to do let's say 0 comma 0 right and let's log here so I log this ra and in the error I'm going to do log and I'll do something like cot and error and then I'm going to render the error dot so this will give us a message I'm going to save it now see what will happen if I open this node space index.js what we are getting that first
we're getting the trying to divide by zero which is this line is getting rendered and then we are doing iners it thing so you're getting the error is getting catch in the catch block and you're getting what CAU an error divided by zero is not allowed and this is nothing but what you're throwing here in this file okay you got it now let's say I'll make this one to 100 divided by 0 which is also invalid so you're getting this but if I just do 0 divided by 10 save it and let's do a clear and I'll do again node index JS so now you're getting a proper result which is rendering here line number 11 right even if I log this so you'll be able to understand save it so you're getting Zer comma result okay so this is how the very basic concept of creating your module single module or how many modules you want you can create and that use in this root component so this is one of the very basic thing now one more thing we need to run U uh learn and that is what how the module wrapper is actually
work see what happened right so in nodejs every module whatever module that we are creating is wrapped in a function before it executed very very important thing and this rapper function we called as a module rapper function right so what happens how this works so this will give you some of the things like this function has some of the parameters like exports require just like we learn module file name and the directory name directory and the file name that which file are getting rendered so how this looks right so let me give you a simple example here so I'll just do here module we do module wrapper so this will be something like this so we have a function and then we'll do a function right and inside this function you'll be having exports then you'll be having the require then you will be having the module which module you're getting rendered then you'll be having the let's say file name and then you'll be having the directory name right so these all the
things you will be having and this will be getting rendered and inside this only your actual module code goes so module code uh let's keep goes here so this first module that you are doing right whatever you're writing first what node just will do they will wrap this module inside this module wrapper and this inside this only your module code will goes whatever you have written here so this is another very important thing now to learn this one right I'm going to just comment it let's save it and let's create one more function here so I'm going to create uh something like let's do uh rapper ex uh rapper Explorer do JS and here I'm going to just simply log some of the things right so log that node module rapper demo okay and then first I'm going to log this so I log file name and
here I'm going to log file name okay let's copy this and let's paste it here and this will be my directory name so I'll do Di and I'm going to do a diir so first let's start with this one save it and now let's create one more function which will be my rapper so let's give this one as raer demo or raer test let's give rer demo.
JS and inside this raer demo first we need to get our Explorer so how we are going to do this one right so first thing we need to do one more thing let's create one more function here so we do module do exports sorry we'll do module. exports and I'm going to export one function here let's do a greed and I'll do a fun function name and I'm going to just do console.
log and I'll do a Hello and then I'll pass this name save it now let's go to our raer demo first I'll need that Explorer so we do rapper Explorer so how we are going to get it so we do require and we need the rapper Explorer okay and now what we are going to do simply just log here and I'm going to log something like in rapper demo.
JS file and let's log here so again I'm going to log file name and I'll do file name let's copy this so this will be my directory name now let's save it and what we need to do right you remember we have actually call this function sorry exported this function now after this I'm going to just call the rapper Explorer and then I'll call this GRE method and then I'll pass my name here now let's save it and now I'm going to just run this so do node because we are in this folder only and we need to run rapper Dem right so do rapper demo. JS hit enter now see what we are getting here the first thing is that we are getting four times okay let
me just quickly change this on ORS for beginners it will be difficult so file name in we'll do in rapper Explorer means this is in a different file right so I'll just copy this and paste it here and this will be in file name in rapper demo file so raer demo save it and let's clear it one more time and I'll run it and let's see what we getting first so first you can see that we getting node just module raer demo which is coming from this file so in this one so file explorer if you notice right this is the absolute path this is the path where I have created my YouTube and then noj full course lesson and this is the file name this is the directory directory means what this is the folder name you can see and similarly if you go to this Raper demo right where we are logging this so in the Raper demo JS file we are getting that file name and the similar directory name and at the end you are getting
hello s mukarji which is coming from this file this rapper Explorer here so this is just I want to explain that how this actually works right so this is how we be getting the file name directory name and all the other things now this is a very basic things uh that you have learned so far so you learned that how you can write very simple nodejs code how to create your module how to export a module how to import a module or requer using require and also some of the basic things of module rapper function in the next one we are going to learn the node module manager or we called uh like some of the things like how to create your package.json how to install node modules and those things right so let's do this one in the next section all right so next we will be learning what is called node package manager right or I think many of you actually heard the term that we called sort as npm so what npm is that npm is the default package manager for nodejs now it allows to couple of things right so first thing is that what you can do you can install and manage third party
packages like libraries and tools and everything right you can manage your project dependencies you can run scripts defined in your package.json file that we are going to learn that how you can create package.json package.json file and everything and also you can publish your own packages right and there are some key npm commands that I'm going to explain first let's go here and then let's create one more folder and I'm going to give this on let's give this as node package manager right anything you can give it's up to you let's close this and let's open uh sorry close everything and for now let's not create anything first uh we need to learn that how we can create our main package. Js file so what package.json file does right so it will basically manage your dependencies and the de dependencies also this package.json file which is nothing but a Json file that contains a metadata about your project so let's say how we are going to create it right so to create a new package.json
inside this folder first I'm going to open in our integrated terminal and let's close everything and here to create it so we need to do npm it okay so this npm in it will initialize a new nodejs project very very important now let's enter let's see what will happen now it will ask you some of the things right so it's asking package name which will keep it like this so you can give some random value here or you can keep it like this I'll keep it ver sign let's give 1.0.0 then I have the description so do node package manager entrypoint index. JSC we have an entry point right so that we are going to create so for now we are going to keep it as index.js the reason is because we'll be creating here one file as index.js if you're creating a different name let's say server.js so you need to mention here enter test command will keep it like this you can give G repository if you have any keywords you can give and then we have author let's give my
name license will keep it like this is it okay we'll do yes hit enter now inside this you'll be having a package. jsn and if I open this one right you'll be having all the things right we'll be having the scripts once you install some of the third party packages you'll be having the dependencies and also the de dependencies right and what is the difference between dependencies and the de dependencies see dependencies are all the packages that is actually required for your application to run in production so you need to have those dependency and on the other end the D dependencies as the name suggest only needed for your local development and in right so that is the only difference now here we have learned one command that is npm in it right so there is another way you will be able to create this package. Json so I'm going to delete this one from here and inside this I'm going to do npm same in it but I'm going to give this hyphen y so what will happen it will automatically create a package.json inside this right you can see now here if you go you will be getting the similar kind of
structure then second thing we are having how you can install a different packages and everything right so for example we are going to use let's say we creating a project and you'll be having you'll be needing some uh dependencies like mongodb or Express or Lotus or anything like that so you need to install that package so that this package.
jsn will keep a track of that package uh that package that you installed right so to do this one we need to use this npm install Command right so you do npm install and then the name of the package so for example your name is a you need to give this one the name of the package and the name of the package has to be there if this package name is not found right so it will give you error for example I'll give some random value here enter and see what will happen what we getting that this package is not found in the registry so npm has a registry right where all the packages are available and this is not found so it will not happen so you need to give a proper name and also you can give multiple dependency name at once but you need to give space so let's say this is your package one dependency space two dependency third dependency so you need to give it like this now let's install a independency so I'm going to install a let's do a Lotus right lus is a very popular packages now here uh we need to give enter now what will happen it will
install see there is a node modules is getting added and also this package dolog will also track of all of these so you can see we have a name and everything and then there is a Lotus is added the version and all the other things this you don't need to know that much like you don't need to change anything here also you don't need to change anything inside modde modules because here you'll be having all the other things what we need to do we just need to use all of these in our code so this is how you will install a dependency R now there are some other commands also you need to do like you can do npm uninstall and the package name so it will uninstall your package and also you can do to up update packages you need to do npm update and the last one the way uh one more important is that to run a particular script so you can see that there is different different scripts right so you need to do npm run and then the script name and whatever scripts is defined in your package. JS and so that will be automatically run so I'll do here so let's create simply one index.js once again the
reason is because in our package. jsn this is our entry point and I'm going to use our packages that we have installed right so install the loades so do const I need loades and to get it again what you need to do what we learn in the previous one that we need to use this reare right so do reare and I need load see automatically it will give you option and example I'll give some name here so I'll do names let's give my name let's give John some other name and I'll do uh okay now what I want to do let's say I want to capitalize all of these so I'll just take one do capitalize and I'll use this loades dot so here I'm going to do a map and here we are going to use names and then I'm going to pass this loaded
dot so this will have a I think it's called capitalize capitalize I think this is correct now let's log this and I'm going to log this capitalize here now let's save it and now I want to add one more script in my package.json and that will be my start script so I'm going to start it so you'll see that there are a lot of scripts that you can add so I start so to start how we are doing here so we do node and then the name of the file right similarly we need to add here so we do node and then the name of the file is index.js and if I now save it right and I'll do npm start enter see what is happening sorry I think it will do the first letter only my B so see first letter are all are capitalized right Alex and Mia you can see so the the main point is not learning this the main thing is that how you can create package. Js and how you can run your start now let's say you can add some other like you can add your da
script and other things that we are going to learn later but this is a very basic way how you can install manage and create your package. jsn now let's move on to the next on next uh section will be very very important so there we are going to learn some of the very basic and very popular module so we start with path module then we're going to learn the file system and then the basic HTTP module okay and after that only you'll be moving to some other things so first let's complete all these three so some of the very basic idea will be completed so that it will be easy to start like Express and those things okay so now let's get started with the path module so let's create one more folder here and I'm going to give this one as path module okay and let's create index.js inside of this and also we going to open this in our terminal so what exactly path module does right so as the name suggest as simple as that path module provides utilities for
working with file and directory paths so let's see how it works with some simple example and it will be very easy to understand so the first thing we need to get our path module here so first we'll get it like const path and we'll do require and we need path okay so this is the module name and here the first thing we are going to do let's log the current directory name so I'm going to do here console.
log and let's give like directory name right and here I'm going to give path dot so the um this is a method so this directory name and here you need to pass the file name so we'll do file name okay and if I now save these right right and let's say run this node index.js and what we are getting simply we getting the absolute path here and if you notice you are getting this path module because that is the directory name and inside this you are having this file name and I think the file one we already know how we are going to get it so to get this one we need to use the path. base name so let's do the file name also so I'll do console. log one more console and I'm going to do I need to get the file name and even this looks very simple but believe me these are all are the very basic concepts so you need to understand all of these so that you'll be able to apply these in your real projects so I'll do path. base name
and again I'm going to pass the file name here save it clear this and then run it again so now we getting index.js okay what else so we can also get some of the other things like we can get the file extension also and to get a file extension we'll do let's log one more time so do console.
log and we'll do file extension and to get the file extension we need to use path. ex name and here we need to pass the file name okay save it and let's clear and run one more time so we getting JS okay so this will give you the file extension now there are couple of other things we can do so you can combine multip multiple path segments into one okay and create one absolute path or relative path also so for example let's I'll create one more Sal const join path and here we are going to give path. join and you can give different path let's I want to go to/ user and then after this I want to merge or join documents this is just example then I'll do node and I'll give something like projects okay and let's log this so L console. log so we'll do here joint path and this will
be join path save it and let's see what we are getting so we are getting the joint path right so automatically it will add all of these and combine and create One path for you also we can also resolve some path right so if you want to resolve path so here we need to use let's I'll do const resolve path and you need to use path.
resolve and here we'll pass let's say user and I'll pass something like documents the same example then I'll pass the node and I'll pass the project so it will check that whether this is uh this path is exist or not and then we are going to resolve this path so console.
log and I'll do resolve path Also let's keep some comment here so I'll do resolve path let's save it and now let's log here so if you see here right we are getting resolve path we are getting video YouTube nodejs and then we are getting this path module user SL node do/ project okay so this is some of the very interesting thing that you can do using this path now the most one used here is you can you'll be using most of the time this path.
directory name and also this join path is also important here okay now what else you can do now let's see one more thing how you can do a normalized path so I'll do const and I'll do normalize path and I'm going to do path dot normalize and here we are going to give something like let's say let's give slash user SL I want to go to/ documents and then let's say I have some other path here and then I'm going to give here again something like node SL projects something like that and then if I just log this so do console.log and I'll do normalized path and let's give some comment Also let's save this one clear this so you can see that we getting SL user SL node SL projects right so it actually giving you this path from here and it is normalizing or B you can say
it's simplifying the path okay and then it it is giving you the normalized path so this is one more thing you can do so what the things that we have learned so far how to get the directory name the file name file extension how you can join path okay resolve path and also normalize path now in the next module we are going to learn the file system or file module and there we are going to apply some of the logic or concept that we have learned so far in this particular path module so let's move on to the next one okay so I understand that how this path module works now let's create one more and I'm going to give here file system file module also you can give I'll give file system and I'll create index.js here and I'm going to open this one in our terminal okay and let's close this okay so again the file system help you to work with files and to get this one first we need to again import it right so we'll give const uh it's always better to give this one as FS so this stands for file system and I'm going to do a reare and here we are going to do a FS
so this is the module name and also we are going to now import our path module also this is just now we learned right so you require path now let's say I want to do something right so inside this folder I want to create another subfolder and inside that subfolder I want to create some files okay so or we can create some text file or whatever so how we are going to do that now again now as I already mentioned that you need to apply some of the logic or concept that youve learned so far so how you can create a module or sorry not model a folder inside this file system right so let's create a data folder here so I'm going to create a data folder and to do this one right we'll do path. join see here we this will help and then what you need you need the directory name so what is the directory name if I'm hovering you can see there is a absolute path is coming here if I over see c/ user and this and it's going till file system so after this I want to add one more folder
which will be my data folder I hope you're getting so what you need to pass here so if I go to this join right so you're giving this path and everything this is some I've given some example but here we need to pass the directory name so I'll do directory name and I'll give the folder name here so I'll give data okay now let's save it now what I will do so this will be my data folder now I need to check that if it is doesn't exist so we are going to create that folder right currently we don't have that folder created here and now here this FS will help you so this file system so I'm going to check at this FS dot so we have exists sync okay so this here we're going to check this data folder so this will check whether this is exist or not and here if it is doesn't exist so I'll do Ms sorry fs. mkd sync now what again this will do this will create a that
data folder right so I'm going to create pass your data folder and I'm going to just do a console.log and I'll do data folder created now let's save it now let's run it here so you learn one one property here till now so I'm going to do mode of index.
js hit enter so you're having a data folder created see it's created right so it's checking that whether this data folder is exist or not and then I'm going to create the data folder now once I create the data folder I want to create a file inside of this so let's see how we are going to do that so to create a file we are going to again you need to give the file path like where you want to create the file so inser this data folder to to do this one I'm going to do const file path and here I'm going to pass path. join and I'm going to pass what the data folder right and I'm going to give a name like example.txt so this will be my name of the file and then to create a file now this is synchronus okay I don't know synchronous I I forgot the spelling whatever you remember so this is synchronus way of creating the file so here we are going
to do fs and the method called Write file sorry fs. write file sync so we do write file sync okay so this will create the file but how we are going to create it so we'll give the path again if you notice right how this is related first we are getting the directory name we're giving the folder name then we are getting the folder name and we giving the file name okay and then here we are going to give the file path and then I'm going to give some text so hello from nodejs and I'm going to log once again so I'll do console.log and I'll do file created successfully save it and let's run this file created successfully and there is a example.txt and if I go in this file we are having hello. nodejs awesome now this is we have learned now how how we are going to
read this content from the file right so we need to get the file content so L con read content from file to read this one we need to use FS dot now you can note all of these methods okay these are important actually and this is called read file sync so here you need to again give the file path and I'm going to give here the property is utf8 okay now let's save it and I'm going to do a console.
log and I'm going to give like file content and this will be my read content from file and let's clear this and I'm going to just run it again so we are getting hello from nodejs so this is what we are having here all right so this is how to write and this is how to read now what else we can do see this is not the only thing right let's say I want to add another line here in this so I need to append another line and to append it we need to use this FS do append file sync and here you're again need to the file path and I'll give a new line here so we give n and then I'll give this is a new line added to that file okay and then I'm going to do again
console.log and I'll do file new file content added save this and let's run one more time so new file content added we getting and if I go here right so you're having a new file being added to this file so this is one more thing you learned so what are the things you learned so far first to check if it's a folder exist so using exit sync to create a folder we going to use mkd sync to re write a file in a synchronous way write file sync to read a file read file sync and to append a new line append file sync now see how you can do the async way so do async way of writing code right so we'll do as sync way of creating the file so use as sync way and I'm going to do here the first thing I'm going to create one more so do as sync file path again I'm going to use path. join I'm going to pass the directory name
sorry sorry not directory name we need to pass the data folder because inside of this data only I want to create and I'm going to give here like a s let's give something like Asing example.txt now to write in Asing we do fs. WR file okay this is not right file sync but right file you need to BU the async file path or the file path here and you need to was the content so I'll do hello as sync nodejs and you need to pass a call back here so this will take a call back so I'll take a error and here we are going to do if there is any error so I'm going to just throw error or else I'm going to just do a console.log that async file is created successfully after this you can do the read and everything right because this is a call back so inside this we going to do first let's see let's save till
this part and let's run one again so we have a sync file now is created and you'll be getting the content now I want to read from here so I'm going to do FS do read file again you need to pass the file path we'll pass the format and then again this will once again give you the call back so do error and the data all right and once you'll get this so here also you can do the same thing right so you can just log this and then we are going to do so the first thing we let's log this data and let's see what we're getting so do console.log and we'll do async file content and I'm going to pass log the data so let's save this clear it so getting Asing file content which is hello Asing noes which
is correct so this is done after this again we are going to inside of this we're going to do fs. append file not sync if you see that is the difference so in this case this is only append file again you give a sync file path and again I'm going to give a new line so I'll do this is another line added right and here again it will give you the error and if error so throw error or else we do console.
log that new line added to async file or as async way or async file let's save it now let's clear this so getting new line added and if I go here right getting this is another line added is this will be whatever so this this is done and what else we can do and if you want to let's say you want to get the updated file content so again we need to use this fs.
read file inside of this so I do again fs. read file and here we're going to pass the file path do utf8 and now I'm going to do error and then I'll do updated data right because your data is now updated so here if throw sorry if error just throw error error or else I'm going to just log here updated file content and this will be your updated data save it and let's clear and run this okay so you're getting updated file content which is hello snc nodejs and this is another line added so I hope these all are the main thing that you should know in the file system so first if the file exist sorry something exists or not so using this create a new folder create a new file using sync way right file sync to read read file sync to append append file sync and to async
way you just need to remove all of the sync rest will be same so write file read file and appen file okay so this is all about these two section now let's move on to the next one so next one we're going to learn the very basic HTTP module all right everyone so let's get started with another module so in this one we are going to start learning the HTTP module now in this particular module right there are lot of things that you can learn but we are not going to discuss each and everything but first we'll uh start learning some of the very basic thing and the things that will be required in our next section okay so first we need to understand how you can create a HTTP server all right and how you can create some routes and then we are going to create a very simple project so let's create one more folder here and I'm going to give this one as six and let's keep HTTP module and let's create server.js okay so first when you will create a HTTP server you need to get the HTTP module here right so this thing we
have learn so for that whenever you need some particular module you need to export it or you need to require that particular module so do con and I'll do HTTP and this will be require so I need HTTP module right now first we you need to understand that how we can create a HTTP server so let's create a server and this HTTP will give you create server method okay so which will give you these two properties that will be a request object and the response and here you will get lot of things for example this request will give you all the properties whenever you will be requesting something let's say you calling an API and you need to pass some pass something in your payload so that it will call a API right it will go to a database it will do something and then it will give you the response back so this request will do all of the things for example this request consist of the param this request you will give you the body and lot of other things okay the
payload and everything and this response is nothing but it will it will return the response back now in a real scenario the example will be let's say you're working on a front end and a back end right so front content will have some form and you will be submitting the form and once the form submission is successful then you will be getting some uh response right whether it is successful or not so in this request you will be passing all the form values or basically the body let's say you have register form and you have input and password so those you'll be getting in this request and you'll do the API call as I mentioned and once you'll get the response back so you'll be passing this response back to your client right and in the client based on this response will understand that okay my response is successful or not and based on that you are going to do something so here uh if I am going to log this right request now this will consist of lot of properties that you can check first one more thing we need to do now will this thing whatever you write will this work no the reason is because this server that you
have created Right This Server should listen to a particular Port so that you'll be able to receive request or and you'll be able to send response back and to do this one you need to do this if I search for do listen right you see there is a server do listen method which nothing but starts the HTTP server listening for connection so that means what we understand that we need to now create a connection here right so we need to create a port right so I'll create a variable and I'll give a port as 3,000 so that means I want to run this server on my port 3000 and then as I mentioned that this server will give you the listen method here you need to pass the port that you are running and this will give a call back so I'll just log here that server is now listening to port and then I'll pass my port here okay if I now save this right and let's open this in our terminal and then I'm going to do what
we need to do node space server.js hit enter so server is now sorry this will be server okay so now let's go here and what I'm going to do right I'll just open this and see what is happened right so you can see that you're are getting the response object which is a very large thing and here you'll be getting each and everything that you need right as a request so all the properties you can go through and the thing what I want to explain here is that you notice right if I go there so you see it's loading continuously and nothing is happening here the reason is because we are not sending any response back right so that is the reason it's continuously loading so we need to send something so what I'll do right in this race I will do a right head so these all are the method or properties of this response object that you'll be getting here this you can go through the to the official
documentation or if you don't want to do it I what I'll say right or suggest that in this whole module or in this particular video we are going to use this response object multiple times so once you'll go through this video and do all of this step by step you will be getting all the properties the most used properties right you no need to know everything in this request object having and it's a huge object you can see that all the properties is available here so the first thing I'm going to say something like this okay I will pass a 200 and here I will do a content type so what will be my content type right so this will be my another property here so this will be content type and I just want to pass a simple text so I'll do text slpl and then I will do what I'll do send so this is to send the response back and I'll sending what I'm sending so I'll do hello nodejs from HTTP module right let's save this and now if you go there right it will still be
loading so now I will go to my terminal let's go down let's run it one more time so I'll do clear and I'll do node space server.js so it's coming here if I now refresh this right okay something we are getting race dots okay okay I have done send sorry it will be r.
end not send okay so that is the reason now let's run it and now let's refresh this one more time so you can see that we are getting hello noes from HTTP module so that means that is the reason that we are sending a response back okay now what we learned so far the very basic thing two things I've have learned is that we need to create server HTTP server using HTTP doc create server we need to listen to a particular port and we learn that how we can send as a response back whenever we will be loading something on this local L 3,000 again this port and everything is very very important the reason is because whatever you'll be mentioning here it will be running on that particular Port only and all of these we going to learn in very depth when we'll move to our rest restful API development right and we are going to use Postman and everything but for now I think this will be more than enough now let's move on to the next one now next what we're going to learn right we I will explain you how you can create simple routes using this HTTP module so let's create a route routes.js
file right so first thing again we need the HTTP so I'll do HTTP will be equals require we need HTTP module and I'm going to create my server so I'll do const server which will be HTTP do create server and I'll be getting my request object and the response the first thing again never forget to run this right until unless you listen to this port this will not work so I'm going to give Port as 3,000 and then I will do server.
listen it will be port and here it will take the call back so again let's log the same thing so I'm going to do server is now listening to Port 3000 the first thing this request object right this will give a request. URL okay so URL is one of the properties of this request object so I'm going to get my current URL from this request.
URL and I'm going to check if this URL is equal toal to slash that means so if I go here right and you can see that if I just paste it here so you can see that you are getting only this slash at the end so that means it's checking if it is only in the base URL or in this local 3,000 so I want to do something right so here I'm going to do I again do race.
WR head and I'm going to pass it 200 and I'll do the content type as text so I'll do text slpl okay and then let's send uh one more so I'll do race. end so I'm going to do this one as so this is my homepage okay okay so now let's save this and now we need to run this file right inst start this so we close the server and I'll do node space routes.
js and now let's refresh this so you're getting homepage on this slash okay because you are currently in the base route else I'm going to do if my URL or the current URL that I'm having if it is in my let's say projects right so if it is in the projects page so I'm going to do a projects page here so I'll copy this and paste it here else I'm going to do something else so I'll save this and I'm going to do it instead of 200 right I'm going to do a 44 and I'll do that this page is not found so I'll do this page cannot be found save this and now again and we need to run it so run this one let's refresh this and now let's go to the projects oh sorry sorry we are passing
homepage here we need to do projects here save it and now let's refresh this so you're getting projects if I go to the route you're getting homepage let's go to something else let's go to about page we're getting this page cannot be found because these Pages doesn't exist so the main funa is not that main funa is how you can create or how um you can create separate separate routes and how we are going we are creating it so based on the current URL right which we are getting from the request. URL so these request.url will give you the current route that you are having and based on that we are sending the response back now currently we are sending very simple response this is not the case but this is just to give you the understanding so till now you have learned quite a few things the reason why I am saying is that because all the things whatever we'll be learning all all of the concepts are very based on this HTTP module and all the other things like file system and path module so all of this is very very important and try to write each and everything what I'm
writing here line by line if you never worked on nodejs this is going to help you a lot so now we learn two very basic things now what will be our next step right so next step will be we are going to learn three or four things I'll say the first will be start with our callbacks we'll learn what is call back hell and then we'll be learning promises as think AIT and then we are going to learn some of the concept of event emitter once we complete all of these four things then we will be moving to our main section which will be our Express so there we are going to start Learning Express template engines and then we'll be moving to our main section again the second main section which will be our race AP development so let's start uh learning all of these step by step from the next part so let's create one more file folder here and I'm going to give this on as callbacks and let's create two more so next will be promises now again these all the section will be very very short because I'm pretty sure that you already have some idea on this call back
promises and as think of it if you know JavaScript but still I will suggest highly suggest not to skip all of this next we'll be having async sorry this will be nine which will be async have it and lastly we'll be having our Event Event emitter so these four things we are going to learn so start with call back right so here I'm going to do one thing first I'm going to create my main index.
js and I'm going to create one file which will be my index.txt and this is my callback logic Concepts save it so now the first thing we need to understand that what actually callx are right so see call if by definition and call are functions that are passed as arguments to other functions now what exactly it helps so call functions allow you to defer the execution of a code unless sorry until after an asynchronous operation has completed now when we are talking about call backs in nodejs it's used you can say like almost everywhere like it's very commonly used for example handling any as synchronous of person such as we have learned the file model right reading file writing file so those all uses callback functions making HTTP request or whenever you'll be doing some quiry database and everything right and call Hill is also
known as so I think it's called Pyramid of Doom something like that and it happens when you have multiple nested call backs for example let's say I'll give very simple right so you have a set timer right and then inside set timeout you're having another set timeout something like that and then inside this you are having another set timeout so what is this so this is a call back hell so you are calling callback inside another callback something like that right so this will be the very basic concept now how we are going to understand right so let's create a very simple function here so I'm going to do a function and let's give this one as uh person so this person will receive two things it will receive my name and it will receive a call back function so I'm going to do call back function right two things and then this I'm going to create one more function which will be uh like I'll give something like address and here uh let's just simply
console log so we'll do console. log and I'm going to just log the address simple as that now how I'm going to create a call right so first thing I'm going to call this person which is my this function I'm going to pass my name here this name is the input to this name and then I'm going to call the call function means in this call function I'm going to pass this address as a callback so I'm going to pass this address here so what I'm trying to do simply so here inside this function I'm going to do a console. log and I'll do something like hello then I'm going to render my name right once this is done as I already mentioned the definition right so this will wait until one one function or one step is done and after this step is done then only I'm going to call my call Web function so here I'm going to call this and then I'm going to invoke it so what we doing I hope you're getting that we are passing
this as input we calling this address as a call back and and then once this function this line of code is executed then I'm going to call this callback function so now let's save it and I'm going to open this in terminal let's close this one also and what is the name so we have node space index.
js right so what you're getting right you're getting sorry I think I logged address here so let me just log India let's clear it and let's run it so you're getting hello s mukari and then we printing India right so this is a example of a very simple call function now the definition from a noes point of view so simply we can do something like this right so let's get our file system and I think this part we have already done so I'm going to do require and then I'll take my file system and I'm going to Simply read a file so I'm going to do read file remember this is a asynchronous way of reading the file right and here I'm going to pass my uh let's do something like this I'll pass my input so this input.txt so this is the file and then I'm going to pass utf8 and then I'm going to take my error and then data now what is this error and data so this is my call workor function
here I'm calling it and then I'm going to do if error then I'm going to just do console of error so I'm going to do error reading file and I'm going to log the error and then simply return from here or else I'm going to just do console. log and I'm going to render the data let's save it let's clear it and let's run it so you're getting callback logic Concepts which is my this text now this is not the point of getting the data just to give example that this is the Callback function we we are first reading it then in the call back we checking if there is error render it or else render the data okay now let's see one example of callback Hill so inside this I'm going to create one more and I'll give this one as callback hill. JS right so here I want to do the following things first I will read from this input.txt from this file and then I'm going to modify this data so this data
I'm going to modify and then I'm going to create one more file here so first I need my file system so I'm going to do require and I'll do FS so first uh let's minimize this so I'm going to do fs. read file and I'm going to pass my input.txt so here again we'll pass the format of utf8 and I'm going to do error and the data right so first let's go here and let's log this part the same thing so in we are already inside one callback just remember this thing that we are inside in this callback already and here I'm going to do cost modify modify file data so here I do data dot to uppercase okay and then I'm going to do FS do right file now see what we are doing and I'm going to do a output. txt i give sorry we need to pass the file
content so this is the file name this is the file content and again inside this we have a call back right and then I'm going to just copy this and I'm do error writing file right and then inside this again I'm going to log this mod log this so look console sorry we'll do console. log and I'll do data written to the new file right so inside this another call back so first we have one call back inside this in the right file we have another call back now inside again I'm going to take one more call back and I'm going to do read file here and I'm going to now read file from output.txt the new file that I have created I'll do utf8 and then again I'll do error and data so I'll do if error so I'll do console do
error so do error reading file and I'm going to return and then I'll do console. log and I'm going to render the data let's save it now first thing what are the things that we have done right so first start from this top level so read file is will give you the first call back inside the read read we have a right file which is another call back so this is a nested call back and inside this again we are reading this which is another call back so this is a perfect example of a call back H now definitely this will work so if I now do this right sorry we need to run this file so I'm going to copy this file name and I'll do node space. js enter so we have output Dot txt which is written and we getting each and everything that whatever you have logged so far now I think uh it's simpler that how the Callback what is callback how you can create a simple callback now
these all are very very very important interview questions also and uh how you can also they can ask you like okay give me some example of call back and call back hill in context of node J so even if you're writing a simple function they will ask you so in that case you can give this kind of example using this file system and everything now let's move on to the next section where we'll be learning two things the promises and how to like create promises and everything and what will be the alternative of promises which is ASN and then we are going to learn this event emits now we learned that call back and call back H right now see promises are actually better way or cleaner way to handle asynchronous code as simple as that when you compare promises with callbacks so so let's see how we can create promises and how we can handle errors with promises so here I'm going to create one more index.js inside these promises I'll close everything else and let's open this in our terminal all right the first thing is
that how we can create promises right so to create a new promise we have this promise interface that we can use but let's uh do this one with a simple example so I'm going to create a function I'm I'm going to do a delay function which will take a timer or time and this delay function will return return a promise now to return a promise we need to create a new promise and what this promise will give so promise will give you two things one will be the resolve and another will be the reject right if there are any error so it will reject the promise and you'll be able to log the error or something and if it is resolving the value so it will come to your resolve block so here I'm going to take my resolve first and what I want to resolve I want to do a set timeout and I will just pass this resolve and after the time that I'll be passing as input after that many time I want to resolve this promise as simple as that so I'm going to pass my time here right so now let's we'll do a console do log and I'm going to do a
promise lecture starts and then I'm going to just simply do call this delay function and I'm going to pass a time of 2 seconds so 2 2,000 milliseconds now what this promise will give so this will give a DOT then right which I'm pretty sure you already know I'm you guys might be thinking that what I'm doing all of this but I think it's important to just revise all of this one more time even if you know right so this will give you then which if the promise is getting resolv so it will come inside this then block or on full field you can see that and here I'm going to just do a console. log because I'm passing 2,000 right I'm going to give it after 2 seconds promise resolved and then after this I'm going to do a console. log end save it and now I'm going to do node index.js because I'm in that folder hit enter see what happened so promise
lecture start and then it immediately loog this console log but it wait until 2 seconds until unless the promise is getting resolved again if you make this one let's say 200 right so it will be very fast now let's enter it see immediately it's so it will be2 seconds whatever so this is the very simple way of creating promises now how we can create uh or catch uh error in promise so let's create one more example so I'm going to create a function here so let's create a m divide function and I'm going to take my number one and I'm going to take a number two and again this will return a new promise and this time I'm going to take my resolve and also my reject so I'm going to Simply check that if my num two that we are having if it is zero so we can't divide by zero right so I'm going to reject here right so I'm going to do a reject so I'm going to call this reject method and you need to give the reason so I'm going to give like we
cannot perform division by zero right else I'm going to do a resolve and I'm going to do num one divided by num two I hope you're getting right so this will now return a promise and we are either rejecting the promise or resolving the promise and to check it we can simply do divide function and I'm going to pass 10 divided by let's say 5 dot then so what will give this will give you result right which will be your promise result or dissolve result so I'm going to log my result or I'm going to catch here so this will be my error block and here I'm going to just log my error and let's do a console do log and I'm going to log my error here save this and let's run it one more time and you can see that we are getting two here which is coming from this one so this result right so if I do your result so
it will coming from there actually so if I now run it one more times so you can see there it's coming from here but what will happen if I just pass your zero save it and now run it one more time so you're getting cannot perform division by zero and error so it's going into the catch block right it will never run this it will going to directly to the catch block so this is how uh we can create promises and also we can catch promises so catch means we need to reject that promise and then when you'll be calling that promise either we can dot then means the promises result so you can whatever value you'll be receiving using that value we can do something or else we can catch that error and using that error we can do some some oper right so this is the basic uh lecture or like Concepts on promises now let's move to the next one which will be my Asen cover so what is ASN ASN is exactly what promises are doing to handle your asynchronous offers right but why you use that because it's like you can say like synthetic sugar
over promises like it's much more simpler whatever syntax and everything you'll be writing right and how you can how you can write asnc and Aid we are going to see that so asnc function that whatever each and every asnc function that you'll be creating it will always always return a promise very very important every time it will return a promise and the a keyword is is only be used inside your Hing function you can't use outside of it right and what that a keyword does so it pauses the execution of the function until unless your promise is getting resolved so let's see one more example I'm going to create index.js inside of this and let's create a very simple lesson function right so we're going to create the delay function only so I'm going to do a function and delay function which will be my sorry this will be my time and again I'm going to return new promise here right because I already mentioned that this will always return a promise Asing function and I'm going to do a set time out I'm going to resolve it and I'm going to pass my time now to do this one we're going to
do as sync function right because we need to give the ASN keyword and I'm going to do a delay gr something like that and here let's say I'm going to get my name first I'm going to call this aate and I'm going to delay it so we'll do delay so I'm going to do delay function of 2000 and I'm going to do console.
log and I'm going to pass my name here and then at the end I'm going to call this delay brid and I'm going to pass my name here let's clear it and let's open this folder in our terminal because we have opened current the promises folder so open and I'm going to do node space index.
js hit enter see what it after some time you're getting that my name right if I one second do see it's waiting for 2 seconds and then it is giving my name so it's delaying it because of this a anding right so this is a very simple way now coming to the error handling how you can do error handling right again we can do that similar this uh example only so let's do here only so what I'm going to do right I'm going to do a sync function and I'll do a division and I'm going to take my num one and num two and then to do this one to catch it we need to take what we need to take try catch block correct so we'll take a try catch here this catch again will catch the error and I'm going to do a console do error so I'm going to pass error and I'm going to log this error and here I'm going to do a return return null and in
the tri block I will do if my num to again once again the same logic if it is zero so what we will do we'll throw we'll throw a new error and I'll do cannot divide by Zer and if this is not the case so what we'll do simply return num 1 divided by num 2 save it and now to call this one right so we'll do as sync function we'll do a main function so let's do main function and here I'm going to do console.
log AIT and I'm call this division method and I'll again call this 10 comma 2 and I'm going to log one more time but this time I'm going to divide by zero and we're going to see what is happening here so let's clear it and let's run it sorry I think we haven't called the main function sorry we need to trigger it main function so now let's see clear it and run it so what you're getting first time you're getting five second we are getting error that cannot divide by zero we are getting null and after this we're getting the previous function my name suum which is different but it's catching the error here right so this is how you can do so what you learned over that in promises you can do the catch block and catch block will give you the eror in ASN it and now obviously each and everything we are going to create our controllers and everything logic we are going to use Asing function because this is much more simpler right and we
going to use it try and catch block so this all the three is very very important things and although you might think these are very simple but it's not all the logic and everything whatever we are going to write in each and every project is depending on these three things right callback promise and as inab it in the next section we going to learn the event emitter and after that we'll moveing to the express so let's quickly see the event uh event section right so see what they're telling that if you worked with JavaScript in the browser you know that how much interaction of a user is handled through events right so similarly using this node this event emitter we can achieve similar kind of functional so what exactly event emitter is right so event meter class is a code module in your nodejs right so what this allows this allows object to emit named events right or kind you can say those like functions or listeners to be called okay now you can see that we have emit which is used to trigger event and then on is used to add a call back function and that's going to be executed when the
event is triggered and inside this call you can do certain operation like for example you need to call some API call or some function at enable but let's see with a simple example and it will be easy to understand so let's go there and we have evener now I'm going to create here index.
js and let's open this one in our terminal right let's expand this and close it and I'm going to close both the first thing again right so you need the events module here so I'm going to do a const and I'm going to give this one as event m and I'm going to do a request so you need the events model and to create your event emitter so I'm going to give my first emitter right so you need to do new event emiter and again as I already mentioned that what this does this will give you this emit method and the on method right emit is to trigger event let's say you're creating a event so you need to use emit and on is to register a listener so I'm going to now register my first listener right so register a listener so how to register so I'm to my first register. on and here you need to
give a name name of that register so I'm going to give this one as grd right and this will give you a call so I'm going to get my name and then I'm going to do a console. log so I'll do hello and then I'm going to pass my name here and to call this uh listener again we need to use this on method sorry emit method not on method so I'm going to just simply do my event my first emitter do Emit and what you need to pass you need to emit this event which is here using this name very very important this is the name of the listener so here you need to was the GD and then you need to was the name because this will take a call back in the not call in the parameter this will take a call right so in the parameter you need to pass I'm going to pass my name here save this and then I'm going to do node index.js so getting my name here now you might think this is a very simple
example but this is very very important like this listeners and everything if you worked with any react native projects or anything right so there you'll be adding lot of listeners so what it will do if user is doing certain acction so it'll be emit event and based on that event you'll be doing certain op persons so this is the very basic way of writing I just want to explain although we are not going to use all of this but if you see if you work with socket and everything right for Real Time data communication they are using lot of listeners and everything uh listeners and everything so that is the reason this is very important now let's create a custom event listener right so I'm going to create my custom one more so here I'm going to create let's create a we'll do custom I'm going to do listener you can give any other name if you want and first we need our event emitter right so let's copy this line paste it here so here I need I'll take a class and I'll do my custom my custom emitter which
extends event emitter right and here we are going to take a Constructor we'll take super and then I'm going to take take let's do these dot uh we are going to take these do greeting which will be hello and then here I'm going to create a method which will be my greet method again it will take the name and here very very important what we need to do this method was doing what here see here what this was doing we are emitting this and then we are doing those Logics right so here in this function I'm going to do this. emit so I'm going to pass greeting and then here we are going to pass this sorry this Dot greting and then I'm going to pass the name that I'll be
receiving here right so this will be my name so which will be let's say I'm passing my my name hello suum okay and then after this what we are going to do simply so here so let's create const I'll do my custom emitter and this will be new my custom emiter which is this class that I have created which is extending the main event emiter from your nodejs events and now because this is a custom one you can simply create your own right so you do my custom editor.
on and what you need to pass you need to pass is greeting this is the name so you pass greeting again this will take a call back let's say uh what we do right so I'll do some input or something anything and here we'll do console.log and I'll do greeting event and I'm going to pass this input here okay and then I'm going to just log this to my custom emiter dot see you're getting grd right because this is where you emitting this so you're going to do grd and then you'll pass let's say my name here now let's save it and I'm going to run this so do node custom listener. JS hit enter so you're getting greeting event which is coming from here and in the input word you are getting if
you noticed you're getting these dot greeting also very very very important now these do greeting is nothing but this it's coming from your Constructor where you have defining this and the name is the one that you're passing in this input again because you're calling this greeting so it is triggering this method here and then you are rendering your name here so we are getting greeting this is the method not this is uh loging you're getting this do greeting if you noticed which is hello and then the name and this is coming from on this greting event so this is how you can create your own custom emitter okay so these two things I want to explain before moving into the express section so now if I recap everything right so you've learned almost all the basic and most used noes model so learn how to write your first noes code the npm packages and everything how to create your package doj and path module file system HTTP call backs promises ASN C and event emiter now in the next section we will be start working on our main things which will be the two things we are going to learn right first we going to learn the express then we are going to
learn how template engine works which is called ejs as a sort then we're going to move to rest API development and then mongod socket lot of things we are going to do so let's start step by step so first we'll start with our Express module all right everyone so now we will start our journey on Express the first thing is that you need to understand what actually Express JS is right so Express JS is nothing but a web framework for nodejs so just like we have reactjs for uh JavaScript something like that what are the main advantages or the key features of Express JS uh this is also interview questions right so first thing is that routing and even if you go to the official dog right and if you go to Route uh sorry the guide you'll see that most of the important topics and some of the very basic concept you can understand from here also like how to write hello word code definitely we are going to understand each and everything in this particular section I have divided each and every uh Concepts in different different uh parts right or chapters so the key features are like routing then we have the
middleware concept template engines like EGS ejs pug then there are a lot of others to generate Dynamic HTML then we have static file serving error handling and creating restful API development right so the first thing what I have done I created another folder uh this is a new project now all of this I'm going to add in my GitHub so you can go there and then just check check in uh the repo and then start uh coding I would highly suggest that whatever we are going to create from this particular module you can write along with me or with this video it is going to help you you believe me or not take your time and this all the concepts I haven't learned in a single day or in a month or three months right this takes time so take your time and uh start learning step by step no hurry the first thing uh I'm going to give right here so let's create we have understand in the previous section that whenever we need some third party Library packages what we need to do we need we need to have some metadata or our package.json which will keep a
track of all the dependencies and everything we'll be creating so here what exactly we need so we need Express J right so I'm going to create npm in it now instead of doing this one I'm going to use a shortcut which will be hypen y hit enter now this will create a package.
json right now here uh I'm going to Simply install so let's do npm install install and I'm going to do Express so now this will automatically install expressjs and let's go here and then we have our Express JS main is our index.js now this is fine and nothing else I think for now this will be fine now what else we need right so first we need to start learning some of the things so first we'll understand how you can create a basic Express server how we can create routes what are the concept of middleware how you can create custom middleware right what are the request properties and then lot of other things now in this section this particular section will be only Basics and the concepts in the next section we are going to learn about the template engines so we'll be learning ejs template engine and after that we'll be moving to rest API development so here I'm going to create my first file and I'm going to give this one as index.js okay let me just minimize this
one now how we can create a Express server right so that will be the first thing so whenever we'll be creating something we need to get that module so I'm going to do a require and this will be my Express here so that I'll be getting to create Express uh sorry express application we need to invoke this method right so even if you go to their code right so let's go to hello world and you can see that they're creating this app here right so this app we need to create this app you can see what they're telling right this line is important that this app start a servers and listen to a particular port and then it send a response back hello world or something like that so similar thing we are going to create here so I'm going to do const app which will be my Express and I'm going to invoke it right which will create express application as simple as that now this app will give you everything you need so you can see here right all of the things all the properties and everything from this app you're going to use it so now I'm going to create my first route which will be
my for my root URL so to do this one so I'm going to do a G Route here and I'm going to do here app.get so I'm going to do slash and this will give us the call back and this we already learned that we have the request and the response object and I'm going to do a rest. send and here I'm going to pass a hello world let's save it now will this work so this will not work right the reason is because we haven't started our server yet so we need to start it so I'm going to take a port which is which will be again 3,000 and then I'm going to do app. listen and I'm going to pass the port this will give us the call back and now I'm going to do console do log so we'll do server is now running at Port 3,000 right so you have the port let's save it so now I'm going to run node
index.js okay we are getting some error oh sorry sorry I think the spelling is wrong right so you have to give notes okay let's do one thing let's remove this one here one here so I'm going to keep only node sorry index.js and then I'm going to again clear it it and I'll do node index.
js so you have now server is running now let's go there and let's run our local 3,000 right so you're getting hello world as simple as that now this is to create a simple your first hello world so what are the main key things we have learned so far now each and everything you'll be learning from this point right it will be very very important like all the things you are going to use whenever you will be creating any backend application using Express so first you learn that we need to get the express module we have created the app so we need to invoke it so which will create our express application and then we created a route end point so whenever I'll go to this slash or my root URL I am sending a response back a hello world and then I'm listening to a port so 3,000 in this case and then I'm running my server right so whenever I'll go to local L 3,000 I'll be getting this response so this will be our first thing that we need to learn now second thing we need need to understand some of the very important modules that you should be using most of the time so let's create
our I'm going to give this on name as app module and it's up to you how you are going to write the notes and everything for yourself so you can write in a notebook or you can uh like uh like write it in in your computer also it's up to you and the naming convention again uh you can give it based on your convenience whatever is easy for you for learning so again here I'm going to copy these two things and I'm going to paste it here and the first thing is that we have we can do couple of things using uh this app right so we can do something like [Music] application application label settings so what are the things that we can do so we can do like app. set so this will give like let's say we want to set our view engine which is our ejs right so template engine we need to give View and then we need to give engine and you can set something like we can we'll set it as ejs so these all the properties that we can do so so this is one next we can do or we can create routing so that we have learned so right
so routing how we can do so we can let's say I'm going to create a g so I do a app.get and then I'm going to do a slash and here I'm going to pass a request response and here you can do like rise. send which will be my let's say homepage so this will be my G now you can also Al do we can also do Post request right so I can do app.
post and then I'm going to do something like let's say I'm passing in this API / dat inpoint and I'm going to getting my request and response and I'll pass a r. Json as a response and I'm I'll be passing like for example message data received and then I'm going to pass my data which will be some random data so which is my request.
body let's say I'm getting from my request. body so this is just to give example okay so these all the things that we can do then you can also do we can also manage some kind of error handling middle Weare so how you can do that right so for example this app will give you one more method which is used and here you will be getting error request response and next now you don't have to worry about all this this what this next is doing and everything this we are going to discuss in our next upcoming uh lectures what exactly all of this things so I'm just giving example like some of the things that we can do here and then you can simply do a console.log and you'll do error do stack so this will give you the particular error and then you can send a response back so I'm going to send uh like let's say I'm going to send a status of 500 that there is error 500 or anything starts with four that means there is error and this is kind of internal server error or if you're facing this and then you'll uh sorry we you will send something like
something went wrong something went wrong okay and then you can we can do these things uh that will run the server and everything but this this part right whatever we have learned so far this is just to give example that what this app is doing if you go to their official dog right uh let's go to their API reference so here if you go to this Express right you will be getting all of this like what are the properties and everything this has right and each and everything like you can see this is a huge huge documentation like lot of things are there so for example we have learned some app. use and everything right that also we going to do so if you see right we have app do uh which one is that so we have app. use that this one so these all the methods so app. post is a method app do gate and everything so this is one more thing if you want to learn more you can go to some particular SE and you can understand everything so these all the things you have understand
so far see we have app. locals app. Mount paath so these all lot of things right uh like I'll also not be able to understand each and everything because I haven't maybe read or haven't applied in my real projects so some of the very very important thing is we are going to use app. getet app. listen then app.
post put see all the things you'll be getting from here some methods and everything now next thing we are going to learn some of the other things right so uh let's learn that how we can create different kinds of routes and this part will be important so I'm going to give this one name as uh app or let's give this one as routes routes module.
JS or routes example not module I'll give so I'll give routes example so we are going to create some of the basic routes so to give uh do this one first we'll start with we need our Express right so we'll get Express and this will be require so I'll be getting my Express here and then I'm going to create my app so I'll do conack so this will be my Express now the first thing uh we are going to create our gate route so let's say which will be our root route right root route which will be app.get and here I'm passing slash because this will be our home URL you say or the main roote URL here we'll be getting request and response and I'm going to send so we'll do raise. send we'll do something Welcome to our homepage save it and then we're going to create so do cons Port so I'll do 3,000 and I'll do app do listen so passport
and in the call back I'm going to just log that so let's go here and let's copy this from here and I paste it here right so let's open this so I'm going to close this so node.js so let's refresh this so you're getting Welcome to our homepage so this part we have already learned in the previous section in the index.
js now what are other things we can do right so let's say uh we have some list of products that we need to get and we can't get each and everything in the same route correct we need to create separate separate routes so these each and everything whatever you're creating each and everything is your AP uh is your each and everything each individual route so here I'm going to create one more route to get to get all products for example right so we do all products so I'm going to do do app.get and here we are going to get let's say SL products means I'm telling that whenever I want to get something from this endpoint as simple as that or from this route and here I'm going to do a request and response and let's create some products right so I'll create products which will be add of objects I'll give ID one and I'll do label as product one so let's copy this and paste it two more times so this will
product two and this will be my product three right and I want to pass something from here and to pass it we'll do raise. Json simply for now and I'm going to pass this products so now let's save it so what will happen right if I go to the SL products so let's see so we go to SL products okay we are getting SL products cannot be found this is interesting okay okay uh this is my bad the reason is because we need to every time we make some change right we need to run it because we are not using anything like node one and everything those we are going to learn later so again we need to run this file so now it will work so let's refresh this okay so now we are getting all this so we're getting Pro product
one product two and product three and the important thing is not about what you are getting thing is that how you're getting it for the beginners if you're a complete beginner right so that is the reason I'm going this much in depth or very simple way that what exactly this thing is doing so when you'll be working on any real life project let's say we working on some react angular doesn't matter anything so you'll be calling this AP end point from your client side okay and then whenever you'll hit it you'll be getting this response back and this response back line is nothing but where you are sending this response back for this particular particular INF if you don't send anything it will not work so now you learned that how you can get all products and now I want to do something else I want to get a specific product so I want to get only let's say id2 product or ID3 product so how you need to do it so in that case now the concept of dynamic routing comes into picture right so you need to pass some Dynamic ID so for example let's say you have some e-commerce project and you
clicking on id2 product you'll go to a Details page so you need to get this id2 right and then this id2 you will capture from your client side and you'll be sending in your server so this you'll be passing as input for example just hypothetical situation not hypothetical that will be the real scenario for now because we not creating we are not having any front end so that's that is the reason I'm explaining that you'll be sending this to your back end and from your back end you'll be doing a API call and then you will be getting this from your database and you'll be sending back to your client so to create a dynamic so to get a single product right to get a single product we need to do something so how we are going to do it so I'll do a get now here I need to do something else so I need to do products but I need to tell something that I have a dynamic value here so how we are going to do this Dynamic value now to do a dynamic to create a dynamic route you need to give this colon very very important very very very important I say right this colon
and then after this you need to give any random value any value but don't give any random value give which is like relevant to this so I'm going to give a ID so what I'm telling Express that this AP Endo that I'm creating this is a dynamic API route so I need to go to My sl products and this ID value will be a dynamic and how they will understand so this is a dynamic because of this colon if you remove this this is not a dynamic route so you are telling that okay this value can be anything it can be one 1 2 3 and four whatever so whenever I'll go to this route I need to get a single product so now in this route we are going to get a request and response right and then I'm going to do const product ID and I'm going to now do a parts int of so request we have params now you'll understand what this params is doing so these params will give you the ID how you will be getting the ID ID the important thing here is this ID name you have given right this ID you need to
get here so it will be r.p. ID if you're giving here let's say inst ID you'll give product ID you need to give product ID again this is you need to give exact if your I is capital you need to give Capital here or else this will not work if you're giving something else you need to pass here the same value right I hope you're getting that whatever you'll be passing here from this value Express will get the dynamic so in the real scenario how we'll be passing we'll be passing like this we'll do products and then you'll be passing SL2 so then Express will understand okay this two is nothing but this Dynamic value so whenever you go to request. params do these it will give you two I hope you're getting right so let's make this on ID so now I'm going to do this on ID and let's copy this products here because we don't have real database or anything and now I'm going to get get single product which will be what products doind so will
product we have product so I'll do product dot ID should be equal to equal to this product ID so what will happen this will give you your current product so I'll do product ID right and then I'm going to check if this get single product is present so I'm going to do a rise. Jon of get single product else I need to do something so I'll do race.
status so 44 is a status code that usually use for whenever you'll not get anything right so I'm going to do a send and let's do like product is not found please try with different ID save it again we need to run it I I always forget this we need to run this one and we'll go here and let's go to SL one you're getting ID product one if I refresh this you're getting two if I gave 20 we getting product is not found even if I just show you right if it is difficult to understand let's log this request.
params here save it now run it once again and I'm going to refresh this so getting request. paramis id20 now you notice right this ID is nothing but this ID value it is taking if I give product ID here and I'm going to pass product ID here save it run it one again and now I'll go to sl3 so now you will be getting product ID instead of ID because you have changed this value so this is how you need to get a or create a dynamic route I hope this will be clear right okay so now this is the only uh this is all about this particular section that where we understand that how you can create different different routes now definitely we haven't uh discussed post request delete request put request all of these those things we are going to learn in the next section
where we'll be creating the uh creating the projects and we'll start our rest full AP development but for now I think this will be more than enough now next thing uh we are going to learn some about uh something about what is middleware and we are going to create some middleware also we going to understand some of the middle Weare function like next function and how it works and then we'll move to the template engine so let's move on to the next one all right so now we will start learning the middleware concepts okay now again I'm mentioning because we'll be creating multiple projects and all of these projects we are going to use middleware so when you'll be doing the Practical projects right it will be easy to understand how that works but I thought it will be much better if we give some very basic Theory and also with some very basic example so that it will be easy when you'll start the projects and everything so what exactly is middleware right see if you see the definition now these all the definition and the reason why I'm explaining because these all are interview questions also so you might guess this kind of uh questions in your interview like okay tell me the definition of
middleware so middleware functions are simply functions you can see that that have the access of the request and the response uh object that we have discussed the only thing that it has it has a next middleware function all right and what this next middleware function does right which will call the next middleware function in the stack okay but now uh you might think okay what exactly all of these we have different different kind of middleware application Level error handling middleware and buil-in middleware also is there and also you can create your own custom middleware so let's start with a very simple one right so I'll go here and then I'm going to create let's create this one as middleware do JS okay now let's close this so first I'm going to need Express so we do require Express and then I'm going to create our Express app right so we do app which will be my Express now I'm going to Define my first middleware so we do Define middleware function so again we'll go by
the definition so middleware are simple functions right so we'll give here my middleware something like that my first middle word so this will be function which will have request response and it will have a next property right so here what we need to do I I'm going to Simply log at that let's do console.
log and this first middleware will run on every request right let's say you want to do some kind of validation here and whenever you want to do or run this middleware so you need to use that middleware right but here the trick and that is you need to call this sorry you need to call this next method here so that it will call the next method or next middleware in the stat back if you go here let's go to application Level you see that they are doing some they're logging some time and then they're calling the next here right so now I want to use this middleware so how we are going to do that now to use the middleware we have this again I already mentioned in the previous videos multiple times right this app that you're invoking or creating your uh express application this app will give you lot of properties one of the most used property is that it will give you this app.use okay so here you are telling that okay every time I will run or go to a particular URL I want to run
this middleware and what your middleware is doing let's say it's doing some validation and based on that it will run the middleware for now we are just console log that is fine now let's going to copy this and I'm going to paste it here so I'm using this middleware every time and this is for all the routes so now I'm going to create let's create some routes so I'm going to create app.
gate and here I'm going to give a slash and so this is my homepage so it'll request response and let's give a raise. send and we'll give this one as homepage right this part we have already done and then I'm going to create one more and this I'm going to give as about page anything about page and this will be my about page now let's create our port or let's directly do this we do app.
listen I'm going to pass 3,000 and this will be a call back and I'll simply log here right so Lo log so window server is now running on Port 3,000 okay we not using any variables we give 3,000 now let's save it so now let's open this right so I'm going to open this one in my terminal this file now let's run it so I'm going to do node space middleware do Js okay so server is now running now let's go here okay let's refresh this page so we getting hom page that is not the thing the thing is that you can see that your middleware is getting run on every time okay I'm going to do one thing okay now let's go here and let's go to the about page so I'll go to the/ about refresh this you're getting about page
this med is again running I'm going to just comment out this x uh next method from here and I'll rerun this one second so I'll do this and now I'm going to refresh this page and what is happening here it is calling this or the functionality you want to do that part of code is getting executed but it's not calling the next stack here and the reason is simple because you're not calling this next function so that is the reason you need to call this next function to invoke or to put the next kind of things that you are doing for example here you we are calling this about me method so this is not getting executed only or this is not being added in the stack so that is the reason you need to use this next method save it I'm going to run it one again let's go here and you can see you immediately get get this right so this is uh the very basic concept not I will say not very basic but this is what exactly mware is there is nothing like some people will think that M middleware concepts are very
difficult it's actually not this is the base concept that it will run every time and you need to call the next medular function using that next function that it will provide okay so this part is done now let's see uh we'll do something right so we'll create one more middleware here so let's do something like this so here let's create a custom middleware I'm just giving the name it's up to you you can give any other name you want and also try to experiment with all this the reason is because right because unless you will not practice by your own it is very difficult to work on a very big project and one more pattern I am seeing nowadays is that uh don't take it personally but all of you are going for like very fancy kind of projects like you'll be asking for like post gra uh like all the other things like Prisma graph Quil all of the all of the things at once in one project see these kind of things are okay but when you'll go for a very big tech company they doesn't work
like that so for example you are working on on a project so that project will be either on Express or either on postgress or either on SQL I'm not telling you that don't learn learning is definitely good but you should learn one thing at once and then you should learn it properly means you can't learn Express and then on the other side let's say you learning Nest JS all of these two things in two days it takes time so take your time and then go for very uh large scale project so first you need to clear your Basics it's very important actually so here let's do one thing I'm going to I'm not going to rewrite everything so I'm going to copy this and then paste it here and I'm going to create a uh let's say we are doing some kind of logging functionality and you need to log a Tim stamp every time you will do some request okay every time refresh the page or something like that so I do here let's create a request Tim stamp request Tim stamp logger right and what this will do we take request response and next I want to do let's I create a time stamp
here let's give a new date right and I'm going to do this one to to ISO string all right and then I'm going to just log this so let's give this time stamp and I'm going to give like from and I'm going to do request do method uh we'll give method and we'll do two I'm going to do this URL so request.
URL something like that okay and then I'm going to call the next method so this is done now what we need to do what we have learned that we need to use it right so do app. use and I'm going to pass the request time stamp logger now let's go here and let's copy this all things right I'm going to keep the same and then I'm going to just paste it here save it and then we'll run this file so we'll do clear and I'll do node custom middleware do JS and now let's go here refresh this page and you can see that we are getting that it's a gate method and this is the URL if I go to homepage and you're getting it from the homepage the point is not that the point is that what you can do right whatever things you are doing here let's say you are working on authentication or something like that so there are a lot of things you can use in this middleware right midd middle words are extremely important and very versatile concept
like for example if you work with nexj or something right so they have a concept of middle we so what you can do that will run on every request and let's say you need to implement some kind of O functionality or authorizations like based on roles so you can run a middleware and based on that you can restrict or you can allow users to access some particular pages so in those scenarios this middleware is very very important so try to practice by by your own and create some more middleware so that you'll be able to understand so this is all about the middleware concept that I just want to explain now what we've learned so far is that the first thing what we learn right which one was the first one so I think in this one index that we learn how to create exppress server right how to listen to a port then you will learn this app model right where we learn that we can do different different things with this app right this app will give you lot of things like do set which will help us like to set our view engine if you're using some Dynamic template engine like ejs or pug there are a lot others also then we have the routing so we can create routings right we can also do use
and lot of other things you can do now I will highly suggest that you can go through this app properties in the official Doc but for now why I explain all of this because this is all what we are going to use in most of the times in your projects also then you learn the very very important concept and that is middleware and how you can create custom middlewares all right so this part is done now what will be the next thing the next thing is that we are going to go to the temp Dynamic template engine section which will be our ejs we are going to understand so what we will do right we'll be creating some uh API routes and then I'll show you that how you can create a UI using that EGS or dynamic engine that we basically say so let's move on to the next section all right so now in this section we are going to learn how we can use this embedded JavaScript templating or that we call EJ JS now there are others also that you can use you can search it but in this tutorial or in this video we are going to only uh follow this particular one all right so what exactly is this so this is nothing but you can consider this as a HTML markup which you are
writing with plain JavaScript as simple as that so if someone ask you what is the definition so ejs or embedded JavaScript will be a simple templating language that lets you generate HTML markup with plain JavaScript right and why it is useful because it can help you to generate Dynamic HTML Pages Dynamic HTML pages in express application right and how you can write Dynamics so you can see that this less than and this percentage uh this whatever tag that we are using right this is to render any Dynamic value inside of this we are going to see this with a very simple example right so what I am going to do so let's do one thing right so let me quickly p pause this I will create one more project or let's create one more folder and there we are going to create a very simple one all right so I created one folder and now the first thing I'm going to create my uh okay first thing we need to create
our uh package.json right so we do npm init hyphen y so it will automatically create and after that we need to install two things so the first thing we need to install ejs right so we install ejs and also because we integrating in your Express we need Express so these two things we need the first thing I am going to create one index.
js or uh let's give this on index.js only okay so now what we are going to do here right so in this Logic the first thing we need to tell Express that I want to use ejs as my view engine now see in the previous uh section we have understood right that all the properties and everything that we can use from the app so app.
set there is a method that we can use which will set the view engine right so that we need to do first we'll import Express so I'll do require we need Express and then I need EGS so not ejs sorry uh we need uh we'll do one more thing we need a path so I'm going to do a require and I'll do a path here now what I need to do first I need to create my app so I'll do what Express and then which will create our express application now I need to set the view engine as what as ejs right and how we are going to set it so we say like this we do app. set and I'm going to tell that okay set my view engine as ejs right so now these will set the view engine now what I need to do I need to create a views see just like if you have worked in react right so what usually the folder structure
look like so you'll be having the pages component and everything so Pages components are will Define the how the UI will look right because here we are writing everything on the server side so we need to create some kind of views right so here I'm going to create a folder and I'm going to give the name as views so this will be my views folder and inside of this whatever UI and everything all the easiest logic we are going to write so now I need to tell that okay this app. set first time I set the view engine so I need to Now set my views and My Views will point to the folder these views folder so I'll do here that set the directory for the views right so do for the views so I'll do app. set and here I'm going to tell that okay set my views which will be what now here you remember we have uh learned that path. join and what we can we can use the directory name so in the first section only we have understood all of these and now I'm going to join these views so now this will tell that okay My
Views will be denoted to this folder this views folder that I have created so that is my second step next thing let's create some dummy data right so I'm going to do something like this I'll create a products so do id1 let's use a title which will be product one now I'll paste this and let's do this one three so this will be product three and this will be product two okay now I'm going to do like this so I'll do that app.
get so whenever I'll go to my homepage I want to do what so I'll do a request and response so I'll do rise now here comes the trick so whenever I'll go to this route I need to some of pass this product list of products right so that in my homepage I'll be able to render this list of products so this response will give you another property or method which will be the render so I'm telling that okay I want to render something in my which path I need to give so inside my home uh sorry views right what I will do so here we are going to create a home. ejs file so here I'm going to create a home do ejs okay and what I will do simply let's take a H1 and I'll give this one as welcome to homepage and then I will give uh let's take a level right so we take a level and I'm going to do list of products now I want to take a ul and
inside this I want to render all the products that we are having so these products okay so how we are going to do this so we'll tell that okay I want to render something on my homepage so I'm going to tell here that home and here I'm going to pass something like we'll pass a title which will be my home and I want to pass my products which will be my these products that we are having okay so this we are rendering on this page second I'll do another app.
get and this time I'm going to do like let's say uh about and here again we'll take request response and I'm going to do let's do erase. render and this time let's create another about component so inside views I'm going to create another about. ejs and here I'm going to just keep like H1 and this is our about page right okay now I want to render this and only I'm going to just pass the title which will be about page so this is done now what will be the next step The Next Step let's recap one more right so first we have created our app we have set the view engine to ejs we set our views which will denote to this views folder and then what we are doing whatever routes that we are creating so on this homepage I want to render my home and there I want to pass this so I want to pass the title as home and the products similarly for about I'm only passing the
title now I'll do what so I'll create my port which will be 3,000 and I'll do app. listen so I'll pass the port and then we'll just log here server is running let's save it now we are passing the list of products in my homepage correct so we need to render the list of products here in my homepage so how we are going to do that so if we go here right let's go to the let's go to the docs and you can see that what they are doing so simply we need to take these values sorry this template system to render any Dynamic values correct and one more thing if you see here right how they're doing they're doing the render and then they're passing the render so this there are different different ways that you can do that so this is kind of uses you can go to the official Doc what this is doing so this is like a script L tag for your control for no output this is for your wh space and everything
and lot of other things like outputs the value into the template which is HTML esap and you can go through all of this and now what we are checking here that okay I'm rendering my list of products here so I will do a user. for each which similarly just like you will render your jsx in your react right so you'll take your map and then you'll just render all of these now another thing we need to understand is that let's say here currently we are having individual component we are having a home about and those things let's say I want to render a common component so let's say we have a common header component I I want to render the header component inside both this home and also in this about it's not good practice to write the same code again and again right so what usually will do in react we'll create a common component inside component folder and then we'll import it in in every component but here how we are going to do it right so let's see how we are going to do it so inside views I'm going to create a components for folder and I'm going to create header. ejs okay and now here let's say uh what
we can do right so let's create a simple HTML and here I'm going to just render a header and I'll do a H1 I'll do ejs template demo so this is my header now I need to go to my my homepage and I need to include this component here include this header component here so how we are going to do it right so take this right you can see that you are already getting this EGS tag because I have some install you can also search for EGS in the extension and you you'll get it see it's coming here right so now I'm telling that okay let's go here just a minute so here you can see that what we are tell using this output the r script value into the template so this we are going to use so I'm going to do this and then I'm going to tell that okay include so I want to include my so we go to components slash header so I'm including my go to the components
directory and then I'm including my header. ejs file here okay so this you need to include now when you do the same thing I'll copy this save it and let's go here and let's paste it also so now we have imported in both the files right so now what will happen whatever header content that we are having we should come in both the pages or both the views so let's see if it is working or not so now let's go here and let's do node do index.
js and now let's go here and okay I need to refresh this so you can see that we getting ejs template header and if I remove this we are getting e template header in both the pages similarly I'll give you one home homework and that is you can create one more components inside of this whatever you can give like footer or like some other sex and product Dil section anything and then try to include it in both the files or both the views and see if you're able to get that content or not so now let's go here and then I'm going to now um render the list of products so I'll take the template here sorry Dynamic template here and then I'm going to do here products the reason we are taking products because if I go here we are having products here right so what I'll do I'll do products dot for each so I'll take single product right so here you need to do if I go to the official Doc right we need to do a ending tag plain ending tag so they're using this so I'm going to use this
one and now we also need to take one Ai and inside this Ali now I want to render my product. title so I'll take one more but this time I'll do equals and what this equals does equals is outputs the value into the template so now I'm going to do product. title and I need to close this and also I think we are getting some error here uh okay because we not closing this one so we need to close this here okay this part is done so adding simple product.
for each now let's save it and let's see what we getting right so let me close and rerun and now let's go here and let's refresh this page we are getting product one 2 and three so you're able to list uh down the products now again because we don't use this in very real life projects or in prod projects we'll be having definitely we'll be having a separate client uh like framework like react or plain JavaScript or angular or whatever but again it's always important to understand all of these things how it will work so I'll highly suggest you can go to the official dog and try some simple example but for now this will be enough again I give you one more homework uh which is that create one more usable component and try to include and another one I'll give you that is you can see that apart from the products I'm also passing this title here and this is I created in that um idea only that you guys needs to get this title in your both about and home okay currently we are rendering this static so what your homework will be try to render this
title which is a dynamic value in your about page and in the homepage okay so this is all about the plain way how you can create or use Dynamic template system in your express application now let's move on to the next one because till this part whatever we have learned this one right so this you can consider as our first section which is completely based on node Basics code node Concepts and also the Code Express J concept now we'll start our journey on rest API development because there are quite a few things we need to do we need to understand how we can create your backend API Logic the exactly what you'll be doing in your real life companies or let's you are doing some freelancing and everything you're not going to do all of this right this is not work what every company uses okay this is a fact most of the companies will have a separate client and you'll be having a separate backend logic so we are going to focus from the next section I highly recommend please don't uh skip any of the things because all the things will be interconnected it's very very important so we'll start with Express restful API development we'll learn how we can create a connect with our mongod
how to create mongod schema and some of the Mong methods and everything then we'll move to uh creating our first project uh which will be a book store something like that then you'll move to authentication sockets then lot of things okay so from next section it will be very very important and please be very serious from the next part all right so now we will start our journey with restful API development right so first what I'm going to do right we will be having some proper structure that how we are going to uh like create models how to connect your application with database whatever database you want to use in our case because this is we are using as a man let's say so we'll be using mongod as a database we are going to understand how you can create controllers or basically keep or separate your logic in one file and then you'll be able to use those controllers or your helper functions to use and create routes and uh also you're going to understand how you can create different kind of routes right for
example like how to create a gear request post request and those things so in the next two section what we will be doing we will be creating a bookstore kind of application okay so what I've done right I created a folder blank folder you can see that and the first thing we need to create our package.
jsn right here so let's start with step by step so I'm going to do npm in it and I'm going to do a hyphen y so it will automatically create our package.json and what are the things that we need here right so here we need only for now Xpress so I'm going to do npm install and I'll do Express so now this will install Express and also we need to change one more thing and that is let's go to our package.
json and I'm going to minimize this one and let's keep this one as app.js instead of index.js and here I'm going to create my app.js so here uh first we need our Express right so I'm going to get Express and this will be and I need Express then we need to create our app so we do app which will be Express and try to do from this part right as I already mentioned in the previous section that uh from this part whatever we are going to write this will be a real life projects whenever you'll be working in a company or you are creating some freelancing project these all the concepts that you need to create and if you notice that I'm doing everything from ground up so that for a beginner like if you're a complete beginner it will be it will be very helpful for you now here you remember that we have understand the logic or the concept of medw right so here uh we need to use the express.js so this Express will give you the middle Weare that you
can use uh in your app.js or basically in your route wherever you want to use that and middleware Concepts also you have understood right how middleware run what is the uses of the next function of middleware and those things so here I'm going to use my middleware okay and what we need to do so we do app.
use so this we have understood that this we will be a method and here I'm going to tell that okay I want to use the express. Json which will be my middleware right so this will Returns the middleware that only Parts as Json right only looks at request when the content type header matches the type location right so this will automatically puras your uh jsn here and that is the reason we are using this medware for all the routes that we'll be creating in this particular file now I'm going to create some uh uh let's create a dummy books array and I'm going to give a ID of one let's give a title of that book so I'll do book one and let's do one more and I'll do id2 and I'll do a book of two right let's save it so now uh what we need to do we will be creating all our files and everything all the routes logic in this file now the reason why I am doing in this particular file you'll understand
in the next section right because if I uh if I start creating all the controllers routes models everything from this particular part you'll not understand okay why we need controller why we need routes right so first we need to understand that okay what is the uses of controller why you use that particular format what is the disadvantage of writing each and everything in one file right so that part you need to understand then only it will be easy so here first I'm going to create my gate get routes so I'm I'm going to do get all routes excuse me sorry get all books so it will be app.get right and here I'm going to give like okay I want to go to the homepage or basically our main route and here this will give us a call back so I'll take my request and response right and let's do something like this uh we'll do like let's do this one just uh this is our main intro route okay so this I'm going to do let's do address. Json and I'll pass a message
that Welcome to our bookstore API save it so this is our first route second thing we are going to create our get all routes so I'm going to create we'll do get all books so here I'm going to do a app.get and I'm going to give class I'm going to do like get books now you can give any name you want let's give g/g is also fine and also it will going to give you request comma response and what we are going to pass we'll simply pass r.
Json and I'm going to pass my books here okay so these books I'm passing whenever I'll be calling this particular endpoint so these two routes that we have created now what we we need to create we're going to start the server so I'm going to do const Port 3000 and I'll do app.
listen I'm going to pass the port and we'll do a console.log that server is now running on Port and I'll pass the port here now let's save it now you already know that how we can run it so we need to do node and then app.js right so server is now running now till this part what we have done we'll go to browser and we'll manually type that uh route and then based on that we'll see whether we are getting the result but to simplify that uh method we I'm pretty sure you already know the postman so Postman is a software or platform you can say that basically use for a API platform for developers to design build test and collaborate on apis right so we are going to use this Postman I already have definitely installed in my device but I'll tell you that how you can do that so first you it's better always that you
create a free account from here once you'll create a pre account you'll be able to download from here I don't know why I think my net is very slow okay let me just quickly change my Wi-Fi all right so you will be able to easily download from here just simply download it and then then install it that's it and if you have a account so they will prompt you to sign in so you'll be able to uh log in using that so now let me just quickly open this Postman and now here we have lot of things now we'll understand couple of things here but this is also a very vast topic right Postman there are a lot of things you can do but we'll try to understand what are the things related to this API development that we'll be doing the first thing is that this is your workspace and here you need to create each and every collection so let's say you create some project so that will be a collection so on top of this you can create a new collection right so let's give uh what we going to let's do a blank con uh collection right so I'm going to click here and here you can give the name so I'm going to give
this one as book store Rest API okay now here what we need to do right first thing you need to understand that okay now I need to do each and every route that whatever I have created those routes I need to test right and you can see that your server is also running on Port 3000 so now we'll go here sorry we'll go here and then click on right click and let's click here if you see we have a add request so click on this add request now you can give the name of this request that what we are checking so I'm going to check my root route right or let's do index route of of bookstore okay so this will be the name and then you can select the type there what kind of type is that so this is a get request right and here you need to enter your url so this will be our Local Host right so let's go here and let's
search for local host 3,000 let's copy this and I'm going to paste it here and now I'm going to just send so what we getting we are getting that message Welcome to our bookstore API and this is what exactly we have given here now why this is working you might think the reason is because your server is not listening to this port if you if you don't like stop this right let's stop this server here now let's try one more time see there is no connection right so you don't have connection to your local so that is the reason it's showing this so now let's go here let's run one more time and now let's go back send it so you're getting this now I'm going to do go here and let's create one more request so I'll go here and do add request and I'm going to do here get all books right so now let's go let's copy this and I'm going to paste it here now let's if you go here right we have this
get SLG this is the route name so you need to give slash getet send it so you're getting two books right because we having two books so this is how you can create your individual route and based on the type you'll be able to change it now there are a lot of things like how to manage authorizations you can add headers here lot of things but for now the first thing we need to understand from very basic right so what we understand that how you can create a route and how you can taste it now let's go back and now we are going to create some more uh routes second thing we need to do is that get a single single book single book means you need to get it based on the ID right so let's say if I give ID one so it will give me the book one if I give id2 it will return me the book two so let's go here and then we'll do a app.get and I'm I'm going to give SLG now remember what we need to give slash colon I already discuss this this will be for your Dynamic and then you
need to give the ID which will be your param so this will be your route and then it will give you the request response and we'll do a const book which will be your books. find [Music] item so item do ID should be equal to what your request do params right do ID see it's already coming here this is because you given ID here this what we already discussed now let's do here what I'm going to do right I'll check that if this book is available so I'm going to do a rise. Json and let's do this one as sing simply pass the book else also you can do r. status let's give a two 200 else we'll do aise do status so if something not found means we need to give phone not4 so that means this cannot be found and here I'm going to pass a Json and I'll do a message and
we'll do book not found please try with a different ID different book ID save it now we need to close and run this also we are going to learn that how we can use packages like node modon so that we no need to run every time we'll make the changes but for now let's run it and now let's go back again I'm going to send this so this is coming I'll go there create one more and I'm going to do a get a single book right and let's go here copy this and I'm going to pass it here and slash we need to pass the ID so let's say I need to get the ID of that particular book whose ID is two so I'll pass two here send this so we getting id2 pass here one send this where we getting id1 I'll give here 10 which doesn't exist so I'm going to send so
I'm getting book not found please type different uh book ID right so this is how you need to get a single now believe me one thing like these all are looking very simple like you think okay what kind of things is that it's very simple but it doesn't matter if you're creating a like projects like Netflix like Enterprise level projects or very advanced level of projects whatever at the end every is a crud crud means create update delete and get right as simple as that so if these kind of Concepts is clear to you you not only clear the interview but also it will be easy for you to work in your company also because again I mentioned these things in between that in your company I can guarantee that you'll not get like a projects that you will think that okay I'll go to a particular company that and I'll get like fully development project it doesn't work like that there is is a chance that most of the times you'll be getting some maintenance projects or you need to do some enhancement and in that project the code is already written so
you need to either fix someone else code so that is the reason these Basics has to be very very clear or else it will be very difficult for you to manage right so this we have understand now what else we can do now let's see how we can create a new book right so we'll go here and then I'm going to create our first post request post means get means what we are getting post means we are posting something and we are updating so I'll do add a new book and here we're going to do app. poost and let's give this one as ADD and this will give you request and response and I'm going to do a qu new book and here I'm going to pass ID so ID will be your books. length and here I'm going to do plus so it will be books. end will be two so I'll give plus one and I'll give a title so let's give this one something like this we do book what is the title
that we have given so we'll do book two so I'm going to give book and then I'm going to do books. length plus one so it will be books three books 4 something like that okay and then I'm going to call this books and I'll PST this new book here so sorry and then I'm going to pass arise.
status of 200 and I'll do a Json and I'm going to pass our new book so new book means whatever book we are adding if it is successful this this will return us this book back if you want you can also do like this the data it will give new book and message I'm going to show that new book is added successfully right let's save it okay okay so now let's open and let's rerun one again so we'll do not app.
js now let's go back and then let's get one more right so we'll go to add request and we'll do this one as add new book now uh we'll go here let's copy this and we'll paste it here so this will be slash add because that is the route name we have given and this will be a post request right now one more thing here because we are mad ually adding this static data that is fine in real project scenario what will happen right you'll be getting this your request.
body and from your body you'll be able to get that content and based on that you will be adding or updating your database now if I go here and let's run it so you can see that we are getting data ID 3 book three and new book is added successfully and let's go to get all books and we'll send it once again so we getting three books I'll go here and just send it one more time see now we getting id4 book for and go here you're getting four let's do one more time send it so you're getting now five and if I send it so you'll be getting five books right all right so this is how you can do a post request again these all are very very Basics but we somehow needs to start from Basics there is no alternative right now next thing what we need to do right so let's do something like this so we are going to update a particular book and this time I'm going to show you that how we
are going to use our request. body to get the content and based on that we will be updating the uh book's content based on a particular ID so let's do one thing so here I'm going to do update a book so I'm going to do app dop so put is a method that usually use to update something right so here I'm going to do slash let's do update and slash ID now again this ID is very very important because we are updating a particular book so we need that ID of that book right so here we are going to do a request we'll do a response the first thing we need to find the book right that which book we need so here we need to do con find current book and this will be our books. find so this will be book [Music] item so this will be book item. ID is equal to equal to this request. params do ID right and here then we are going
to check if this find current book is present so we are going to do here find current book do title and now this will be this title let's say I'm updating this uh book one to book one Z something like that so I'm getting the ID here and based on that I need to update this title from book one to book 10 right so this is what we'll do so we'll check that if this request that we are having body if this title if this request body contains title so it will pick from there or else it will be the existing title that it has so we do find current book. title and once this is done we are going to simply just do race. Json let's do a status of 200. Json so here we'll do that message book updated let's do like this we'll do book with
ID and we'll do a request. par. ID updated successfully and we're going to pass the data which will be the F current book if this book is not found because that is possible right that you have a two books with ID one and two but you are giving a ID of five so it cannot be fine right that book is not present so we do else we do a rise.
status of 44 dojason that we do a message of book not found save this so I hope you're getting this and then we going to run it one second close it and run it one more time we'll go there and I'm going to create one more request so I'm going to do update a book so let's go here copy this I'll paste it here so I'm going to do this one as update SL I want to update the first book and this will be a put right now see what will happen first I'm going to just send it here okay see book one is updated successfully it's telling but it's existing the reason because we haven't passed any request do body correct so you need to go to the body let's go to Raw we have a Json and I'm going to do this one as title right so sorry we'll pass a title and I'm going to do this on
something like uh let's do this on as book one from 100 let's do do this one as 100 so I'm changing this title from book one to book 100 I'm going to do send so we are getting a book with id1 is updated successfully and this is the data we are getting now let's go to get all books and send request see what you're getting book 100 correct so these ID is not successfully updated let's go to update book let's do a two and let's do this one as 200 send it it's updated let's go to get all books send here so now you're getting 200 if I go here and let's give 200 here and still I'm passing this here but if I send this we are getting book not found because there is no book with ID 200 because we have only two books with ID one and two right so that means this is working fine so let's go to add new book and if I now send it right so getting updated get all books send it I'll be getting updated here but these
values sorry this title you can see that it's all are the update uh data that we have actually called to update the book this one here okay so now this part is done now what else we need to do we need to understand one more that is a delete request that how we can do a delete request right so let's quickly do that one so let's go there and let's create one more request here okay so we going to do a app.
delete and I'm going to do this one as delete and then I'll pass ID because we need to delete individual book with the ID correct and then I'm going to do here request response first again we need to find the book right so we're going to get the index of that book so let's say I want to delete the first book so index will be zero second book index will be one so look const find index of current book which will be books do find index so L item so this will be item. ID is equal toal to request.
params do ID and here we are going to check if this index is not minus one that means that book is present so we're going to do if this is not equal to minus1 so we going to delete it so do const deleted book and we're going to simply do books the array do splice and we're going to pass the index and I'm going to delete the first only one item and then we're going to pass rest.
status of 200. Json and I'll do message that book deleted successfully and I'm going to pass here let's say data which will be deleted book of zero element else we are going to pass that book is not found so we'll do the same thing copy this and we'll paste it here save this and now let's run it once again so I'm going to go here let's add a request and this will be a delete request so this will be delete a book and let's go here let's copy this and I'm going to first search do with delete and I'm going to try 200 send it so getting book not found I'm going to do one
here send this book deleted successfully we getting the data let's go to get all books send it so you're getting only one book if you noticed now let's go to add new book add one more okay I'll add one more more now let's go to get all books so we getting three this ID is same because I think that calculation every done that is uh like we need to change it we can create unique ID also but that is fine uh let's do uh now check uh okay let's quickly do that I think that part what we can do right so we'll go here this new book so I'm going to do a math do floor of math. random into uh let's do a 1,000 and I'm going to pass this one also here save
it and now let's run it one more time okay now let's see let's send this one we'll be getting two let's add a new book okay uh some random value is coming but that is fine now let's go to get all books now I want to delete with this ID 680 so now let's copy this let's go to delete or a book so I'm going to pass 680 now and I'm going to delete this one okay we are getting book not found this is interesting okay I got it why is that because we need to do this one to let's do this on to two string let's save it now let's run it one more time and now I'm going to go to first let's start with this one get all books let's add a
new one okay now we'll go to 734 send it we'll be getting 734 delete and I'm going to do 734 so book is deleted successfully get all books now this should have two books now so you're getting two books now go to add new I'm going to add one more 579 now let's go to update book so I'm going to do 579 and here I'm going to do this one as book 5 79 and then we'll give two Z just for checking and I'm going to send it so book is now updated so we are getting this title let's go to get all books send it so we getting three and now I'm going to delete it so I'm going to do 579 so do 579 send so it's now deleted successfully get all books we'll be having now two books so with this we have completed the croud functionality means how you can get all books or
basically get anything it doesn't about books it can be products it can be recipes it can be what ever things you are working so how to fet all the things how to update a thing how how to add a new and also how to delete also how you can get a single one right so all the things we have understood now I think this part if it is clear then we'll move to the next part so from the next part we'll start with our mongodb Concepts and after that what we're going to do right we will be now structuring this particular project properly now I'll come to that uh thing that why we need a proper structure why this is a this is not a best way the reason is very very simple because it's a very simple project and you are writing each and everything in this file what will happen if you're creating any projects any application like Amazon so it will have multiple pages so if it's a multiple Pages what will happen if you're writing everything it will become extremely messy like you can't even think about it how much messy it will become so that is the reason we need to organize our controllers our routes our model or
database in other files and then we will try to keep our app.js or basically our root file as clean as possible so that is the reason why we should not write each and everything here but at the end whatever we'll be doing in the next part it's nothing but this thing what we have done now okay so these all the things now what we'll do right controller means if you see right this is your route correct now here we are going to cut this logic from here so this is your Handler Handler or helper which will your controller and we going to move this to a different file and then we're going to import it in a route file so what will happen your routing will be much more cleaner and then we're going to use those routes in our app.js and we're going to see that how we are going to do it from scratch so let's start first we'll start with our mongodb Basics and after that we'll start with our first project which will be this bookstore API uh R API development so before uh we'll start with our bookstore project so first as I already mentioned that we are going to
understand some of the basics of mongodb how to connect your mongodb database and how to like use mongus now first of all you need to understand what exactly is so that is the reason I actually created this section and in this section we are going to understand some of the query example the most used query example that we usually use while creating any monri application or any node application using mongus now what exactly mongos is right see mongos is nothing but it's basically used for your object modeling for mongodb whenever you'll be creating any nodejs application as simple as that if you go to their official dock right you will get lot of things like how to create uh Define your schema create model right what are the query helpers and how to uh do error handling and lot of things but obviously these all the things we'll be learning step by step when we'll be creating some of the projects so in this section let's start with a very simple one so what I'm going to do right so you can see we have this uh restful API development uh this is the uh place where we
actually uh created all these routes right so what I'm going to do right so let's do one thing I'll quickly create one more folder I think that will be better so that in that folder we'll be creating like some or mongodb Basics and then we'll be learning some of the query example and after that we'll move to the bookstore project all right so I just created one folder right so let's do one thing let's start with creating all these so first we'll do NP minut uh so we are going to create our package doj and from this part I'm not going to repeat all of these because in the past couple of Parts whatever we have learned so far we have repeated these things multiple times and I'm pretty sure it will be easy for you for now now the package.json is now created and now we are going to Let's install mongus so we are going to do npm install and we'll do mongus all right now first thing you need to understand that how we can create a mongod project right so the first of all what we need to do we are going to use this mongod Atlas so you need to just simply create your account using Google or whatever you want to create and there you'll be getting your
organizations where you will be able you'll be basically the admin and here you'll be able to create all the projects now definitely I have lot of projects that I created so what we going to do right I'm going to create a new project from scratch so we go here and let's go below and let's click on this create new project so let's click here so let's give this one name right so what we'll give let's give this one as nodejs uh I'm going to give this one as mongod Basics okay and then uh click on next now project owner I think okay you are already been selected here you don't need to do anything let's click on Pate project now once you create the project the second thing what we need to do we need to create our cluster right and once you'll create the cluster once the
cluster will be created it will give you connection URL that you are going to use to connect your database in our application so we are going to do create and here there are some options now many of you actually ask me that which option should I create for project like your college project or something definitely every time it will be free there is no point of using the serverless or whatever paid version create free select here and give the cluster names I literally keep it like this cluster zero and you need to select a provider so I keep it like AWS reion it will auto Auto Select so you can keep it the same whatever it is giving the option here and then you can give some opt tag as optional like what kind of things you are creating like its application or environment whatever and it's optional so we are going to just do all of this and this is uh important like select free version and do create deployment once we'll do create deployment this will take some time once this is done you will be getting the uh connection URL back now here we have a
username and the password that we need to use and this username and password is required whenever we'll be connecting our mongod with our application so I'm going to copy this username here again it's up to you you can change it and then I'm going to paste it and I'm going to give this one as 2024 okay and then we'll do create database user and then you need to do choose a connection method so if you select here right you'll be getting lot of options like mongod for vs code or what other options that you want to use we are going to use this vs code but for now I'm going to close this because this is being created I'm going to show you one very interesting thing that I think many of you may fa like sometimes you'll see that mongod connection is not working and you will be like scratching your head like okay from where this error is coming and that is actually coming from your network access so you need to go to this network access right if you go here you'll see that there will be some IP address that will be linked to this particular uh cluster now if your current IP address is not active here there is no way this mongod connection will be successful from vs code so you
need to check this so what I usually do right I'll go to this add IP address and for the time being for practice purpose I'll always do allow access from anywhere but this is not recommended what you should do you should add your own IP address of your machine okay this is I just want to mention for now I'm going to do allow access from anywhere and click on confirm okay so now this will be active in some time and let's go back to our database and let's see what is the status okay see it's taking some time once this is done right then we going to go back and then we'll uh start implementing so what are the things we need to do first the first thing is that if I go here right let's create our app.js and let's go to package. Js and I'm going to do this one as app.js close this so first we need mongus right so we going to get our mongus so we do require so we need mongus okay and now once we'll get the
mongus these mongus will give you a connect method and using that connect method you will be able to connect your application with your database so let's quickly see the status I think it's still being created let's wait for some to pause and then once this is done then we'll start implementing awesome so now I think this is done so now let's click on connect and let's go to mongod for vs code and you can see that you're getting this URL connection URL that you need to use and there is a DB password with bracket you need to just replace it with your own password all right so now I'm going to just copy this and let's go there let's see first how we are going to do a connection set right so we'll do mongus do connect and here you need to pass the URL and there are some options that you can use so for now simply okay what you have done first I'll pass this and then I'm going to just change this part right remember you need to not only change this one you need to remove this black uh this less than and greater than this also so you need to remove completely copy this and paste it here
and remember the password is 2024 right so save it so now this will be done and if it is successful so this returns a promise right so here you can just simply just do that console.log database connected successfully or else we'll just log the error right so we do console.log and we'll log the error so this is done and now once the database connection is successful so what what will be the next step right so if you go here first you need to create a schema right so this mongos will give you this schema property and using this you'll be able to create a new schema so you can see that new schema and then all the properties now these properties will be based on the project that you are creating example let's say you are creating a login form and in the login form you'll be having email and password right so based on that you need to give the key name and the type that email will be a type of string password will
be a type of string let's say you have a price price will be type of number uh you are having some array of object so let's say comments so comments has a body which will be string and date date is a type of date so I'm just giving example that this is how you need to Define your schema so now let's quickly create a new schema here so I'm going to just do const and let's create a user schema so user schema so we understand what so we'll do new and we'll do mongus and this will give you schema right so this will your schema and here we need to pass all the properties so first we'll start with let's say this user will have a name property so which will be string so after that let's say it will have a email which also will be a type of string let's give a age which will be type of number let's say we also want to check if the user is active or not so we'll do is active which will be a Boolean and also let's give a tags which will be arrrow of string right and then we'll give one more which
will be created at that user is created at what time so here I'm going to give a type so here you need to give a type so type will be of date and you can pass a default value like what will be the default value let's see you are not passing this uh I'll give you one more example let's say you are creating a react application and every time uh you will be creating a new user let's say you don't want to pass this created at so it should take some default value so that even if you're not passing it from your front it will be always taking the default value from here so here what we'll pass we'll pass our date do now right so this will be the default value that's it so now after this we are going to create our user model now again again I'm repeating all of this you may think okay why I'm doing like this in each and every like in single file again we haven't we haven't started any project yet these all are the concepts so that is the reason I'm creating definitely we we will be having a separate file for all of these so this will be inside a model file then you'll
be having controllers routes and everything that you are going to see in the next section so now I'm going to create our user model so we need to create the user model right so create user model so we're going to do const and I'm going to give this one as user and this will be mongus now to create a model you need to give a model and this will take a name okay this will take a name which will be this in your database it will be stored in that particular name whatever name you give let's say you give this one as user so this will be the collection name in your database that I I'm storing all my user in this user collection definitely it's very very important you should give a relevant name here let's say if it's a user but you're giving products there is no point right so you need to give proper name here and then pass the user schema that's it so now this will create your user model and now what we'll do right let's create a simple function here so I'm going to do asnc function and I'll do run run queries queries right run quiry
examples so here we'll take a try we'll take a catch okay and at the end uh for catch I think let's log only the error I think that will be fine so do some error and this will be error and then we'll take a finally and we're going to just do AIT we'll just do mongus do connection and then we're going to close this connection right so this is the method to close the connection so this is done now we'll start with our very very basic like the first one is how you can create a new user very very important right and at the end don't forget to invoke this method so you need to invoke it so do run query examples now first we need to understand how you can create a new document right so creating a new document this model you need to see everything you are doing your model is
your like main entry point where you need to take reference from what I mean by that let's say you are creating a new user so you need to use this model and this model will give you all the methods that mongos will provide right and that will coordinate with your database and that will stored in your database as simple as that so here I'm going to keep create a new user so I'll do new user and I'll do a it and then you need to call your user model so this user is this don't get confused and now if I click dot here see what is happening you see you're getting lot of things like you think okay what the hell is this now these all are the methods that you can do different different things that mongos will provide right so here you can see there are some star is there so these stars mean these are the most used method right so that's why I mentioned that it's not that much simple to learn everything in one go you needs time like I'm also I I'm definitely don't know everything in mongod or mongos right
because you'll learn once you'll create lot of things and then while creating lot of projects you'll be learning in the way it's not like everything you'll learn so what we're going to do right we'll be learning very very important important methods first we'll do a create what this create does this create will create a new user in your database right so this will be create and here what you need to pass now here you need to pass the whatever things you having in your model right so you need to pass a name email age is active tags and create a ad so I'm going to just copy all this okay now see I'm not taking the created ad so I just want to show you that if you're not passing this it will always take from your default and then I'm going to pass it here and in the name let's start with my name so I'm going to give my name here email I'll give some random email age I'll give like let's say 25 let's give 40 whatever although I'm not 40 years old that's okay but e
active is true and tags I'm going to give let's say I'll give this one as my developer also I'm a designer right so I give developer designer let's give manager everything and now let's log here so now this is going to create a uh new user right so we'll do let's keep created new user and I'm going to pass this new user here right now let's save it now there is another way that you can do so so we can create a new user using new keyword and then call the save method so now first thing let's go here and let me just quickly see one thing let's go to queries so you can see that you are getting all these methods here and also if you go to the documents right so here you can see that there is a new schema whatever they're creating new my model and then here see this save method this is what I was telling that you can also use the save method to save or create a
new one but let's quickly see how this is working right so I'm going to open my terminal and now let's run node app.js hit enter let's see what is happening awesome so you can see that we're getting database connected successfully and I already created a new user now noticed the tags and everything and there is a created which is taking the current date now one more thing you'll be thinking okay what this is so this is a ID unique document that mongod will provide this is known as the object ID so this ID is unque to this particular user as simple as that and this is not about the user this will be each and everything that you'll be creating every time mongod will give you this ID property if you go there and let's now I'm going to go to browse collection and you can see that there will be a user collection or is created and here you're getting the this user right so this is the first thing now another way that you can do where that I just want to show you
quickly that you can do something like this right so okay let me just copy this we are going to use this this only but I just want to show you that you can use new user so do new user and then you need to call this AIT then you'll do new user Dot and you can see that you'll be getting this save right so this will also save the user if you now let's do one thing let's give this one as raj and let's do this one as raj save this and I'm going to run it one more time okay let's do no app.js hit enter so you can see that this user is created and let's go here and refresh this so getting two now so one more is created here right so you can see that both are giving same idea and everything
but those are the two ways so either first you can create a new instance of that user right and call the save method or directly you can just call this user. create so we'll keep it the previous one only so I'm going to comment out this one here and we'll keep this one save it so now this is first thing you have learned right what will be the next thing next thing we need to let's say get all the documents that we are having here so currently we having two user and you let's say from your front end side you need to get all the two user and you need to display in your UI so you need to get all of this right then only you'll be able to pass it so for now we are going to do get all users right so let's do const all users and now again as I already mentioned every time that you need to play with your model only so this model user model will give another property which is called find right and what this find does this find will give you all the documents now here you can pass some properties like if you want to get some specific Fields
so you need to pass here but if you pass nothing or let's say empty object so this will give you all the all the users that you are having so currently we having two users so now we'll just log this right so let's log here and I'm going to do all users save it and now let's clear it and I'm going to do node app.
js hit enter now let's see what is happening I want to show you so you can see that you are getting three users and that makes sense because what is happened this this thing whatever we are having right this run again so it created one more user but that is not the point every time we'll be doing it will create one more user that is okay but I want to just show you that it is giving you three three data here if if you see right okay I want to do one more thing let's do one thing right let's comment out so that it will not create every time new user or else it will be creating and it will become messy so I'm going to comment this part for now because I hope you're understanding how you can create a new document I'll comment this one now let's save it so that it will be easy and I'm going to again clear it and we'll do node app.js let's see what we are getting so you be getting one right you are getting two and you are getting three so this is giving you all the three user and this
ID will be unique 100% it it has to be unique so if you notice this will be unique always and if you go here and refresh this you'll be getting now three users okay so this is done now I want to do something right I want to do like let's say I'll create one more user quickly and for that user I want to keep e active as false and I only need to get those users whose is active is as actually false means I'm actually targeting a specific field right so how we are going to do that so now let's quickly do let's comment out this part and here I'm going to give this on name as now let's give John do right so we do John do so that it will be unique so I'll give John do right and I'll make this one as false I'll remove I'll only keep developer and I'll give 23 okay and now I think this is fine now let's log
this where we are logging this okay let's log this and let's save it first I'm going to run it one more time so that it will create so we do clear and we'll do node app.js so now let's refresh this so you're getting four now and John E activ is false awesome now what we'll do we'll simply comment out all these right so both the so that it will not give or create new users now I want to get some specific things from our documents so I'm going to do const get users of active false right so I want to get only those user whose Act is false and we are going to do AIT and again you need to do user. find and remember I told you right in this
bracket if you're passing a specific field it will give you that users back so here I want to do look I want to get my e active see it's already going option e active has to be false and I want to get those many users only and I'm going to just log this get users of active for false whatever this name naming doesn't make sense you can change this okay uh now let's run it see how many we are getting so we're getting only one right makes sense because we have only one users but I go there I'll make this one as true save it and I'll be getting three right so we have three users whose Z active is true so now we getting one two and three so this means right whatever you'll pass here it will automatically filter that specific criteria and this will give you that data back okay so this you can do using user. find and pass his specific
property here so this we have understand now what else we need to do so there is another method that is also very helpful and that is called find one so what exactly that find one does that actually finds the first document that matches the criteria right so let's say you're having five person whose age is 20 and you're using find one so it will give you always the first users right and let's see how we are going to uh understand this one so here I'm going to just comment out this part and let's do one thing now I think if I go there so okay what I'll do right it will be easy I'm going to create one more users with joho and for that user I'm going to change the email as joho one and age I'll make this on 25 and isactive I'll do true okay I hope you're getting that what I'm trying to do so that it will be easy so I'll do joho I'll make this one as one I'll do this one as 25 and I'll do this one as
true we'll save it now let's log this if it is creating or not and let's run this so do clear we'll do no node app.js so one mode will be created here so now we have two jondo and now let's see what is happening with this find one okay so now I'm going to comment up one again this part and comment out this part also save it and let's go here and let's say I want to get my John do user so do get John do user I'll do AIT right I'll do user.
find and you can see that we are having one right and here what you need to pass that I want to get the user whose name is what so name is John do okay this one let's copy this so whose name is joho now let's log this and let's see what we are getting right so to get John do user save it we'll clear it and we'll do node app.
js which one you're getting you're getting the first one right this is what I want to explain that you're getting the first one always it will return the first document which matches the criteria correct so now this thing we have learned now what else we can also learn uh sorry we can also do one more thing that let's say you are having 100 users right possible like not 100 like there can be lack or thousands users you want to get some specific users with this ID and this is a real scenario that most of the times you need actually need to do it that need to pass the ID and based on that you need to get the specific users right so how we are going to do that now to do this one right now see we have already created some users right and those users have a unique ID so I'm going to show you how we can do that so first I'll go to the top let's do step by step and I'm going to create one more users and let's give this one as uh let's do something like Travis and I'll do Travis let's give
this one as 55 and this thing is fine and let's comment out this one and I'm going to comment out this also so first I'm creating one users which is this with this Travers name now remember this new user will give you what it will give you underscore ID property which is this ID right so you based on this IDE you'll be able to get it so now after this I'm going to do something like this that okay const get latest uh get last created user by user ID and here I'm going to do a it and we'll do user dot see we have a find by ID and here what you need to pass can you guess so because on the top we are creating this new user right so this new user will give you the ID property and that we have learned actually first time we have checked that so I'll pass here new user and if I do dot so here it will
give you the ID property see so first it will create and then it will come here so ID will be always already present and it will give you the uh this user back so now I'm going to log this so do get last created user by user ID save it and let's see what is happening right so I'm going to do node app.
js hit enter now the reason this is coming from the first so first it created the new user and notice this ID so this this is the ID right and this ID we have passed there and because of that you are getting this data back right so don't get confus this is the first console this is the second means I pass this ID here now let's say I want to do something else I want to get my first user which is this ID right so this also you can copy and you can pass there it's for homework you can copy and pass it and you'll see that you'll be getting s mukari so whatever ID will be passed based on that data you'll be getting so another thing you have learned that how you can do get data by ID right so you need to use this find by ID all right now what else we need to do so there are a couple of more things uh we will do so let's do this one in the next part all right so next uh let's understand another one so for example let's say uh there is one scenario where what we need to do right we need to specifically get
only the name property and the email property but we don't want to get the ID property right so we need to select some specific Fields so let's say how we are going to do that so let me just comment out here now after this we'll take const and we'll do selected fields and we'll do AIT and we'll do user.
findind so this will give you all the users and now here we have the Select Property that we can use right so you have select and now we need to give the properties that you want to select so if you go back we can have name email so we want to get our name so I'll do name then we'll do email but I don't want to get let's say the ID property so you need to give this minus so what this minus does means you don't include this property and here I want to give that don't include the ID property okay and now let's log this so L console.log selected Fields now let's save it clear this and run this and let's see what you're getting so you can see we are getting name and the email but no other properties are coming and you can see that ID property also it's excluded so it's not added there okay so we learn one more thing what will be the next
thing next thing uh let's say you want to so you are implementing some page in ENT and for a particular page you only want to render 10 10 items right and let's say you want to skip the first two items something like that so how we are going to do that so here we'll do one more so I'll do const and I'll do limited users so we do AIT we'll do user do find so find will give you all the elements now you can pass this object empty object here you can't pass this it it is actually similar and here you are basically limiting that I want to only get the five users but do this that you need to skip okay so I will skip the first user okay so this will return only five users but it will skip the first users okay and now let's see what is happening so let's log this so we do limited users save
it and let's clear and run it one second so if you it is giving all of this right travas jondo and then we are having this but you see the first suum so the first user that we created that was with my name right so that user is not coming and the reason is because we are skipping the first user so this is one more property that you have learned now what else now we can also do a sorting right so these all believe me these all are very very important right and whenever you'll be implementing some paging and and sorting you need to use these properties only so now let's say we want to do some sorting here so we do sorted users so here I'm going to do AIT and I'll do user doind so get all the users and then I want to sort it so you need to use the sort property and you need to tell that by what you want to sort this right so let's say I want to sort with age and I want to sort with uh descending order so I'll pass age here so that means I want to sort and
then I'll give a minus one so this will be in descending order and now let's log this so we do sorted users save this and now let's clear this and I'll do node app.js and see what is happening so you can see that we getting 23 25 40 40 and then 40 and then 55 and 55 okay so all of these you are getting in the descending order now here if you pass this one as one it will be in the ascending so let's see that save it and now again I'll clear this and run it once again so now you can see the max age is coming at the end right so this is how you need to use okay I think why this is happening I'm pretty sure we have kept this uh see the that's why it's creating new user
every time let me just comment it this one anyway this is fine now what will be the next thing that we want to understand so let's do one more thing let's say how we can count documents that how many documents we are having so let's say we have this scenario that you need to count those many documents where the use active is true so let's do like this we'll do count documents and here we'll do AIT we'll do user dot count documents and here here I want to pass that use this e active as let's let's do this one as false and let's log here so do count documents save this and then I'm going to clear it and I'll do node app.js so I believe we'll be getting one users with this false right and now I'm going to make this one as true and run it once
again so we getting nine users so using this count document it will give you the number of documents that uh based on some uh certain criteria that you'll be having all right now what else now we can also do like this like you can also delete and update now update and delete we are going to understand much more deeper way when you'll be creating that bookstore project in the next part but for now let's quickly see the delete one quickly so what I'll do right let's do one thing I'm going to do a new user and I'm going to do this one as let's say deleted users something like that means I immediately want to delete it right and this will be deleted user let's give this one as 75 and let's go below and I'm going to do const we'll do deleted user and this will be AIT right and also let's comment this this sorry let's comment this part so that we'll understand that first it
it should create the user then it should delete it so I'll do user right and here you need to use this find by ID and delete see find by ID and delete and here you need to pass the ID so ID will be getting from our new user do ID right so new user will give you this ID property right and then we're going to do log and I want to log here that deleted user which will be this deleted user save it and now let's run it one again and let's see what is happening so first it is created the user and immediately it's deleted also so this user will not be present in our database even if I go and refresh this right and then if you see we have last this travas we don't have the deleted user all right now what else is left now one more thing that is important and
that is how you can update it right so let's remove this and let's understand update part also although again I'm repeating that we are going to understand this one much better so I'll do updated user and just give some name I'll give updated and let's go here and after this I'm going to do const update user so first I'll do a it and we'll do user do find by ID and update see find by ID and update so here what you need to pass first you need to pass the ID right then you are going to pass that what are the properties that you want to update and then it will return a new new object right and that options return the updated document so let's say how we're going to do that so here I'm going to pass my new user do idid so this ID will be created and let's say let's do like this so here I'll take a k brackets and I'm going to do a set property now what I want to set let's say I will set the age uh let's do this one as 100 now
again I'm keeping this one some un relistic value so that it will be easy to check and also I want to do a post property here and let's do this one as something like we have a tags right remember that we have a tags and here I want to do a updated all right so this is done now after this we need to pass the new property so here we going to pass new so this new will be true so this new will return the updated document or user back so let's save it and now I'm going to just log this so console.log and I'm going to do updated user and this will be updated user save it and now I think we are logging this part right okay we are already logging this is okay also I want to do one more thing quickly now we are also logging here now
let's clear this and we'll do node app.js hit enter let's see what is happening so now first time if you noticed we are creating the age with 75 but here it's updated to 100 awesome and then tags while creating the user have given developer and here it is you can see that we are pushing one more which is updated so this is now updated here in the tags go here and refresh this so now you're getting 11 and here you're getting updated user age is 100 and we are getting developed and updated so now uh we have learned quite a few things right lot of methods and most of the methods we have actually covered here and that is the reason I mention right that this this section will be also very important now from this section whatever things we are going to learn we'll be using most of this method and if you're not skipping this particular section believe me it will be like piece of cake for you it will be very very easy okay so now from the next section uh we are going to create our
bookstore API the same one that we have done in the previous section but in that project what we have done we have done all this in one file right and we discuss that why we shouldn't do it in one file instead we should divide and do it in a proper structure so from next section we are going to do that part so let's start working on that particular project all right everyone so let's start with our books.
API development right so I already created a folder and also one more thing I have done and that is I created one more uh mongod database now the reason why I haven't showed you the process I want you to create your own mongod database by yourself right so here I already have the connection URL and this one we are going to use but before that uh we need to create our package.
json right so we do npm in it hyphen Y and now after this we'll be creating our main app.js now this time let's give this one as server.js go to package.json and now let's do this on server and then also we going to write a start script so start with we will be doing this server.js now before that I want to show you one more thing now you remember that previously till this point whatever changes we are doing uh we need to every time stop the server and then rerun again so that the new changes will be reflected but that is not a good way of doing and that is very irritating also right you are not going to do every time you do some change again restart so for that we have this utility that's called node modon so what this does right so this will automatically monitor your changes right in your source and this will automatically restart your server that's it so this one we are going to
now use so let's go there and I'm going to copy this and we're going to install this one right so do iph I save Dev so we'll install as a Dev dependency okay so this is the first thing we need so now this will be added here what will be the next thing so next we need couple of things right so first thing we need Express and also we need mongus that's it and now one more thing we are going to use that we called as EnV so that also we going to discuss that why we need to create our EnV files and everything so these three things we are going to install as a dependencies right all right so this is done now till this part we haven't worked on proper folder structure right each and everything like we have created inside server.js but that is not the way so how we are going to manage our project see normally in projects we'll be having this kind of folder structure right so
we will be having a database folder so inside database folder we will be having the database connection right so here I'm going to create a folder now and I'm going to give this on name as database and let's create inside this db. JS now it's up to you you can give database. JS also so this is our first step what is the next thing that we need we need our models what exactly models models are our mongus models right remember in the previous section we have created our user model so because we are not creating everything right so we need to structure project so that each and every model we'll be writing inside models folder so we'll be creating One models folder so I'm explaining each and everything that what is the use of that particular folder then we will be having our routes right so each and so for example let's say you're having a very complex application uh where you're having multiple you need to work with multiple collection let's say some e-commerce project so you'll be having products you'll be having card you'll be having checkout you'll be product details so for each and everything you'll be having different different routes so that you're not going to write each and everything on one single file
and it will become messy so that is the reason we'll be having a routes folder right and at the end we'll be having another folder that is to write our logic right so each and every route will have a Handler right so that request and response so those things we are going to write inside a controller so that controllers basically handle our main code logic that corate or basically connect with sorry not connect that uh work with your mongod database and then that controller we are going to use inside our outs so we going to see how we are going to do that definitely so I'm going to create a controllers folder here so this will be our main structure now here uh let's do one more thing right so we also need to add some G ignore and everything but here I'm going to create another thing and that will be our EnV file so for example why we need the NV file let's say the mongod the mongodb URL or let's say some sensitive information some token and everything whatever we'll be using in our project we are not going to push those changes in our GitHub right so we need some kind of environment file for that so this is our structure now what else we need to
do so we can create some helper functions also helper folder also so that helper folder let's say we're creating some utility related to time or time stamp so those things instead of writing in your controllers what you can do you can create one more folder helper and inside that folder you can write all of this then at the end we'll be having another folder folder that we call middleware so whatever middleware related Logics that we'll be writing we are going to write inside that folder so this will be our proper structure of writing code okay so first uh we will go to our server.js now why we will go to server.js so we need to first run our server right so let's go here and then first we need our Express and I'm going to do require so we need Express next what we need to do we need to create our app so I'm going to do const app and this will be our Express and we're going to invoke it which will create our express application right now next we'll be having a port so
here now we need our envirment variable so here now I'm going to create a port here and this port will be our 3,000 right so this will be our Port that we going to use and to use this one what we need to do right we need to use thatb package that we have created so dob thatb package will give you all the uh access to your uh environment variable so let's say if we're using process.
env. Port so this will give you 3,000 and let's always do it in the top level so on the top of the server because see why we are doing in the top level the reason is because server .js is your root file so here we're going to do require so I need envy and then this will give you the config so this config will give you all the loads.
EnV file that contains the process. EnV by default correct that's it also you can see they're telling what uh let's go to where is that go to here that uh if NV key is present it smartly attempts to load encrypted do env. VA file contains the process EnV whatever but for now we need these EnV files that we created the name has to be en EnV whatever key value pairs or the EnV envirment variables that we are using it will automatically load here and we are doing in the top level so now what I'll do I'll do a process. env. port right and this port will be this 3,000 and if this is not present then we are going to do a 3,000 by default right but we already have processed NB so it will take from here now after this what will be the next step so next step will be we need to connect to our database right so here we need to connect to our database right
previously remember we doing in this file only but now we already have a folder that we've created for this db. JS right so here what we going to do so first we need to get our mongus right so Lon mongus and this will be require so we need mongus and I'm going to create a method right so L const we connect to DB this will be a sync method and here we are going to Simply do a try and we'll do a catch right so here I'm going to just do a console.
error so we'll do mongod DV connection fied we are going to pass the error and then uh we are going to do a process do will exit from it okay that's it now inside this Tri block we are going to use AET dongus and remember we have used this connect method and this connect method we need to use the URL right so I'm going to copy this I'm going to paste it here and replace it with our DB password which is 2025 that's it and now just log this that mongodb is connected
successfully that's it but now what we need to do we see now we have understood in the first section the the beginner label we have understood the module. export and import right now we need to do module. exports see that is the reason I told you that you need to First learn or do step by step and now it will be very very easy all right so now let's go back to the server.
js and now we need to import it so do const connect to DV and this will be require and we need to go to database and DV do JS right done and now how we are going to do it so simply just invoke it here as simple as that right so now this will automatically connect to our database so once this is done after this we need to use our middleware now this here we are going to use the express.
js middleware that we've understood it which will Parts your Json information so here I'm going to do app.use and I'm going to use express.js right so this will middleware which only passs the Json correct and after this at the end we're going to do app. listen and here we're going to pass the port and let's pass here console.
log server is now running on Port then we going to pass the port so this is the thing that we need the basic structure St uh setup now we need to run it but previously how we used to run so we'll do like node and then we'll do server.js hit enter mongodb is connected successfully server is now running but again if I make changes again you need to stop it and restart right remember so now this node mod will comes into picture so what we're going to do right we'll go to our package.json and here I'm going to add one more script and let's give this one as da so we're going to run the node mod so we'll give node mod and we'll tell that node mod that okay tell me which file I need to run so I need to run server.js if you're giving this one as index.js give index.js giving app.js give app.js whatever so we'll do server.js what the hell man we'll do
server.js so I'm telling that okay when whenever I do npm run Dev so I'll run this script you run nodon server.js see what is happening now so I'm going to do npm run div oh sorry let me just clear it now I'm going to do npm run Dev so normon is now running server is now and mongod is connected successfully awesome now if I go here right and let's do one thing remove this now save it see it's restarted now server is now running so changes you're immediately seeing again revert so you no need to every time run the server again so now we nodon is taking care of that okay so this the basic structure is done so what will be your next step see this is how I usually do the this kind of backend project so first you need to do basic structure and after that you need to do the DV connection so step by step that we have done and after that we need to create our models because whenever will be
creating any routes or controllers we need to work with models right so in the next part we'll create our models so we'll create our book model and after that only start working with controllers so let's start working on the models part all right so let's uh create our models so go to inside models folder now and I'm going to create here so let's give this one as book.
JS okay now the first thing here also we need mongus so I'm going to get mongus which will be require mongus and then we're going to create our book schema so do book schema which will be new mongus do schema and now we are going to pass all the things that we needed so let's do one thing so let's say book can have a title so here I'm going to pass now the title will have a type of of string the required property so now we are going to understand some of the properties that this has to be there so title is a mandatory property so here we're going to pass required as true and then we're going to pass a message like book title is required okay here we are also going to pass stream as true and let's pass a max
length property so here I'm telling that okay this title should have a Max length of 100 and I'm going to pass a message like book title cannot be more than 100 characters okay so this is our first property now let's copy this and let's pass it here and next we'll be having a author the book author okay so this will be also type of string requir will be true and here I'm going to pass author name is required okay and then let's remove this max length here what else we need now let's add one more property and this will be year so from which year this book is written for example some hypothetical situation so here I'm going to pass a type which will be number here we are going to pass reord so reord will be also true and we're going to pass that let's say
publication here is reord okay and here we're going to pass a mean property so mean I'm going to pass as 100 sorry not 100 let's give 1,000 and then I'm going to pass year must be at least 1,000 and also we going to pass a Max property here so max I'm going to pass the Max has to be the current year so we do new date Dog full year right and here I'm going to pass one message like that year cannot be in the future right so this will be our Max year next we're going to pass one more which will be create a DAT so here I'm going to pass a type which will be date and now we have already discussed that we can pass a default property here right so default will be date do now that's
it so this will be our book schema okay now here we are going to create so we'll do module. exports and we'll do mongus do model and I'm going to pass book so this is our collection name and we're going to pass our book schema so here we're going to give let's give capital and I'm going to pass this one as book schema right so this will create our schema now what will be the next step so we have created our DB connection we created model now next step you need to identify when you'll be creating a project okay how many routes I will be having and based on those many routes you are going to create the controllers so now let's go to our routes first now why I'm telling routes is important because based on the routes you'll be creating the controller so first you need to analyze that okay these many routes I will be having for these books so here let's create I always give the name like this I do book
routes.js okay and now I'm going to create here book controller.js first thing we need to go to book routes and here we need our Express so first I'm going to get our Express and this will be require so we need Express and then we need to create our router here create Express router so to create Express router so here I'm going to create const router which will be Express and this will give you the router right so here this will create your router and based on this you'll be able to create all the uh routes that we need so what are the routes we need here correct so let's create all the routes all the routes that are related to books only okay and now I'm going to create so
router dog so first we're going to get our all the books so I'm going to do SL and I'll do books okay or let's do this one as get so we'll do get so we'll get all the books and here we need to pass the controller name so I'll keep this one as empty we need to pass the controller and we we are going to see how this works next we'll be having one more so we'll do router doget and this will be to get by ID so single single book we need to get right we have already discussed get SL and we're going to pass the ID so this will be our individual book ID and here we're going to again pass the controller next we also need router. post so this will be to add a new book right so we do add and here we are going to pass again the controller next we'll be having router dop put so here we'll be having update SL ID so we're going to update based on ID and we're going to
pass the controller and at end we'll be having router. delete so this will be/ delete SL ID and we're going to pass the controller now you might think that okay I'm telling controller controller multiple times where are the controllers so now for each and every route that we are having remember we used to do this request and response the call back here right the request Handler sorry not request Handler the call back here and then based on that we'll do what exactly what kind of operation that we want to do for this particular route so now instead of doing in this route file we are organizing the code in a better way and we'll be writing everything in the controllers so here we going to create all the controller so let's start with the first controller so do const get all books and this will be asking so we be getting request response right and let's copy this paste it so this will be let's say get book get single book by ID okay next copy
this we'll do add new book and let's copy this so we do update book update single book and let's keep this one only update and at the end we'll be copy this and we'll keep delete do delete book right so these will be all the controllers that we need and now we are going to do module do exports and we're going to pass all these so get all books then we'll get single book by ID then we will add new book book then we going to do update book and also you're going to do delete book save it so now this part is done now what we going to do go here in the routes and we need to just map it okay whenever go to this SL gate I want to call this gate all books when I'll go to get single book I'm going to call this get single book by ID and here I'm going to get all
of these lons so ler and let's go to controllers book controller and get all this look get all books get single book update delete and add new book all right and at the end we are going to just map it so I'm going to tell okay when I'll go to get here so I'm going to call the get all books when I need a single book I'm going to call get single book when I do add new book I'm going to call the add new book controller when I do update I'm going to to call the update book controller and when I'm going to do delete I'm going to do delete book controller now I I hope it will be crystal clear to all of you right so why we have created all these routes and then we are going to write all the Logics and database interaction and everything in this file now this is not done yet so we need to always export this router right or else it will not work so I'm going to do module. exports and believe me this I will always forget
and I'll be getting errors so never forget to export this router because these routers now we are going to use in our main server.js because currently server.js doesn't have any routes correct so we need to use those so the first thing what we're going to do we need to import now this book routes in our server.
js so let's quickly do that so I'm going to do here const I'm going to do book routes and this will be reare so I'll go to routes and let's go to book routes so now this will give me the book routes all of this right now what I need to do I need to create my routes here so we'll be creating all the routes now you see how much cleaner this file is this file don't hold most of the Logics so we have segregated all of these in multiple files so now I'm going to tell that okay now go to do app.use and let's go to/ API SL books and then you use this books router sorry books routes so what I'm telling here now this part is very very important you need to understand so I'm telling that okay when I'll go to/ API SL books I need to call this books route but how it will work so if you now open the book routes you'll see that we have
a gate here so I'm telling that okay when you'll go/ API SL books SLG you call this get all books when I'll go to/ API SL books /g get/ ID I need a single book when I go to / API / books SL add I'm going to call the add new book I hope you're getting so this is your parent route and this is your individual route so when we'll be calling let's say I want to call the delete book example so I need to do like this so I go to/ API SL books and then you need to merge your delete route here so delete and then you need to give the ID so this ID will be the book book ID let's say 1 2 3 4 whatever so when I'll call this URL it will trigger this delete book controller and this delete book controller will hold your mongod or database logic I hope now this will be pretty much clear right so this is what exactly we are doing so now we have completed most of the things what we need to do now now we need to interact with our database so we are going to write all these Logics the
controller Logics and then we're going to test it using our Postman so let's do that in the next part all right so now let's start working on the control rollers so the first thing we need to start working on the add new book so that we'll be able to add a new book and then after that we are going to start working on the gate all book so how uh we are going to add something right so till this part whatever logic that we have learned so far in the controllers in the previous section we are using some static data or some static array and then we test those using Postman but now in real scenario what will happen you'll be having a front end and let's say there will be some form so user will be entered some form data and that form data you need to pass to your back end correct and that you are usually receiveing your request object where you'll be getting inside your body and that body whatever value that sorry the form data that you'll be receiving that you are going to store in your uh database but how that will work now see if you go to the models right that depends on what you're passing in your model for example let's say I want to create a new book so I need to
understand that okay what are the properties that I need to pass so I need to pass a title I should be having a author I'll be having a year and also I'll be having a created at which will take a default value so even if you don't pass it it will always take the current date that is fine but now let's go to the add new book and let's start with our first controller right so how we are going to do it so first we need to take always a try and a catch block and here in the try block right so first you are going to get the data so let's say I'll give this one as const we'll do uh get form data something or let's do uh new book form data and this will'll be getting from request. body right so this will have the form data now in this form data what are the things that you'll be having you'll be having all this right you'll be having a title you'll be having author you'll be having year and then it will be you'll be having a created at again I repeating if you're not passing
the created at it will take the default value and now what we going to Simply do so we'll do const and I'll do newly created book now again I'm passing this one like this or else I'll show you what you can do so here you need to take AIT and now what we need we need the model so every time you need to work with or play with your model as I already mentioned so here I'm going to import this book model which will be let's go to our models and then book so here you're going to do a book and now see in the previous section we have understood all of these methods that we've learned right so there is one method that is create and in the create you need to pass this new book form data which you'll be receiving now again instead of doing like this you can directly pass this request. body also here right that will also work but I just showed you because you'll understand that okay we are getting from this request. body now this form data I'll pass here now this will okay let me just quickly change this this will be created so this newly created book will be now created or stored in our database
and after this we can simply check that if this is true right so we'll do if newly created book if this is created so we are going to do a race. status of 2011 and then we going to do a Json and I'm going to pass a success as true and I will do a message so I'll do a uh book added successfully right and I'm going to pass a data and here I'll pass this new book form data okay and in the catch for now let's log this error now let's save it so now I just want to check okay sorry now we need to pass this newly created book not this one so now I want to test this that whether this is working or not now let's go to our Postman and let's we need to create one more collection now remember we are we have created this project using some static data so from what I'll do right I'll rename this here so I'm going to do this one as rest API
Basics and let's create one more collection here so I'll do blank collection and here I'm going to give this one name as bookstore bookstore API okay now let's create our fast out and I'm going to close everything else let's close all this okay let's save all this so now let's go to our book store API and create our first request so this will be our add new book so this will be a post request right and then we are going to just uh copy this URL from here so let's copy this and we'll paste it here and this will be now we need to go to our routes and we need to check that what exactly we are using route to trigger this add new book so you're using SL add but will this work no right because we have
discussed this in the server that we have this/ API SL books so first we need to go to/ API slash books then we need to do slash add so now here this will be adding the new book but now we need to go to where need to go to body we need to go to draw and then we having this Json and here I'm going to pass this let's pass a title so I'll uh I'll do here like first book added what else we need now we need to go to our model and let's see what we are having we are having a author so I'm going to add a author and I'll give my name then we are having the year so let's add ear of 2022 now if you notice that we are not passing the created act because this will automatically take the default value now I think this is fine and now let's send this and let's see what is
happening awesome so now we are getting success true book is added now successfully and you're getting the title back author here the ID I already mentioned and you notice that created that we are already taking the current one right so no need to add this specifically so this is how you need to test it so now we have a new book added in our collection so now what will be our next step so next step is whenever you will be adding a new uh something you need to get all of this right let's say you are creating in UI so you're you are having a form you're adding something now you need to render all the books or it can be a products it can be recipes whatever see again I'm mentioning all of this I'm right I'm creating a book store project doesn't mean that it only you'll understand book related thing it's not like that these Logics are applicable for any level of projects it can be a complex project because I already mentioned at the end everything will be Card application only all right so now what we are doing we need to start working on the get all books so here now we need to get our list of books so let's see how we are going to do that so first we need to
again take a try catch and here first thing can you guess how we are going to get all the books now see these all the concept you need to apply whatever you Lear learn somewh in the previous section to get all the books we'll do const we'll do all books and here you need to do a it you need to take the model so do book and then what you need to use you need to use find remember we need to use find and then you need to pass if you don't pass anything what will return it will return all the all the collections right even if you pass empty object doesn't matter so now this will give you all the books so now we're going to check if these all books do length so if this is greater than zero so we'll do a raise. status of 200 we'll do a Jon and we're going to do a success as true and I'm going to do a message of like book uh we'll do list of
books f successfully and after this we are going to do a data and here we are going to pass all books right now one more thing is that if the length is less than zero so what happen that means the books are not present in your collection so we do else we'll do rise. status now uh we already discussed if some collection is not present we'll do 4 not4 right do Json and we'll do success as false and let's do a message of no no books found in database or collection whatever you can give for now let's log this error and here I'm going to do a raise. status of 5 500 so do Json and we'll do a success as false and we message I'm going to show as like something went wrong please try again and same thing
let's use it in this add new book also so now we have created one more so now let's go to our Postman and let's create one more right so we'll do add request and I'm going to do this one as list of books Let's go there copy this and here now we need to do let's check our route so using SLG get so it will be SL API SL books and then SLG and now simply send this see what we getting we are getting one more right so now this is working fine so let's check one more time so we go to add new book and now I'm going to do a second book added and I'll give something else we'll go John do and I'll do a 2023 let's send this so book is now added successfully and if I go to list all books send it so now we are getting two data so this is your first book
added this is your second book added awesome so now the gate all books or to F list of whatever you want to face this is how you need to do so what we are doing simply we are passing empty object and this is telling that okay I need all the books now again I already mentioned in the previous section that if you need to do some filter or something you need to pass some specific values or specific fields that you want to get now next thing we need to do get a single book right so single book how it will work so it will work means we already discussed this that we are going to get our ID so if you go here we are getting SL get/ ID so this ID will be this ID of this book so this is the ID right if you see here this is the ID so if you pass a single book so I want if I want to get the first book so I need to pass this ID as a param and then I'll be getting this so let's see how we going to do that so let's go to book controller and in the get single book by ID I'm going to take a try let's take a catch and in the catch let's log
this okay and here first we need to get our ID right so again I'm doing another extra variable so that you'll be able to understand so we do get current book ID and this will be request. params do ID and this part we already discussed that how this ID is coming because we have given this param value as ID and then we're going to do const book details by ID and this will be AIT and now which property that we can use book dot can you guess so we need to do find by ID right because we are doing find find by ID and here we are going to pass this G current book ID which is our ID now if this book is is not present so do if book details by ID is not present so here what we going to do simply we are going to return that rise. status of
44. Json success we'll do false and message we are going to do like uh book with the current ID is not found please try with a different ID or else we are going to Simply send it so we will do rise. status of 200 do Json we'll do success as true and we'll do data which will be the book details by ID so this is the book details the current book that I'm fing so now let's save it all right so now let's go there and let's taste it right so we'll create one more and let's copy this and we'll do book details by ID let's paste it and here this will be
let's give slash oh sorry uh let's remove this and then we'll go to list of books and I'm going to copy this and now let's paste it here and send it so you're getting the second book here based on the ID and let's go there and let's copy the first ID and we'll paste it here send it so we getting the first book added I'll change this one to let's say 7 to9 send this one we're getting book with current ID is not found please try a different ID let's change to five let's see see okay so this is working fine now now let's add one more new book so I'll do a third book add it John do one send it so this is added let's go to list all books okay now we are getting three and let's copy this ID now let's go to book
details ID and we're going to paste it here so now we're getting third book okay so that means this part is working fine so we've completed three part the first one is we have completed how to add a new things to your database how to get the list of things from database and how to get a specific thing by ID from database why I'm saying uh saying things because this is not about only the book it can be anything it can be product it can be recipe at the end it the concept is same also I want all of you that instead of creating this book right you can do something else let's say create a recip app by yourself and try to apply this logic then only you'll be able to create larger projects right instead of jumping into very complex project immediately first start with a very basic one so now what will be the next step right so let me just quickly minimize all this so three part you have completed now we need to do update and delete so let's start with a delete now for delete also if you go right we have a delete and then we need to pass the specific ID then only you'll be able to
delete a particular book so let's say how we are going to do that so the first thing again we'll take a try and catch and let's go there and just copy this and then we are going to take our ID so look cons get current book ID which will be request. params do ID right and then we are going to Simply do const deleted book and which property we need to use see the reason why I'm telling all of this again and again again and again the same thing the way I've designed this course if you notice that the things that you've learned in the previous section those things we are applying in the next section now what will happen this way it will give you confidence so that you'll be able to apply the things that you are learning here instead of checking this part immediately you should pause this video and try to find that which property I need to use from our so that I can delete this particular book so it will be book dot we have discussed
find by ID and delete remember so this we need to use now here it will find the ID and then it will delete that book so here what you need to pass you need to pass this get current book ID right that's it and after this again if the book is not found we are going to show the so leave this deleted book is not found right so we do raise.
status of 44. Json we'll do a success as false and we'll do messages like book is not found with this ID else we are going to do a race. status of 200 do Json we'll do a success as true now again this format I'm doing right this success true or whatever this you can change it based on how your project once or based on your project specific criteria you can change all of these right and here I need to pass the data so data will be my deleted book means the current book that I have deleted let's do okay sorry this will be deleted book okay this also will be deleted book all right now let's save it and now let's see if this is working or not so we go there let's create one more let's copy this and let's I'm going
to create one more request and I'll do the delete book by ID paste it so this will be a delete request right so delete and then it will be not get it will be delete remember so if you go here right so delete method and then we have a delete and then ID so now let's say I want to delete the last book that I have added this one so I'll add this one sorry copy this go to delete book by ID and I think that is the one we are having here okay anyway and then send it see it's now deleted correct now we'll go to our list all books and let's refresh this or send it once again so now you're getting two data and it is working fine all right so now delete part is also we have completed what will be the next step next will be our update so once we complete this update means our crowd functionality will be till now whatever you have learned so you should be able to create a very simple project using
crud like how to create how to get how to get by details how to delete a product or whatever things that you are using in your project and also how to update now let's start with the update one now how the update functionality will work right so to update again see let's say let's think in this scenario let's say you are having a form uh this book scenario you are having a front end form where you're having a title you're having a author you are having a year now there will be a edit button and on click of this you want to change the title from one to something else you want to change your author from one to something else something like that so whatever properties you want to update those updated values you need to get where you need to get in your request right you'll be getting again in your request. body and based on that you are going to update it so now let's do that so I'm going to do a try I'm going to do a catch and let's log this for now copy this and we're going to paste it here now first thing we're going to get our
form data right so we go updated book form data and this will be request. body after this we're going to do const updated book this will be AIT then we're going to take book and remember we have this method find by ID and update right here so what are the things you need to pass if you if you go here you can see that we are using update and then we are passing the ID now this ID will tell that which book I'm actually updating so we need to get the ID so we get the ID also so get current book ID which will be request. params do ID and here we're going to pass this so what it will take right so here you can see that sorry it will take the ID that which product or which book I want to update so I'm going to pass this get current book ID I need to pass the values or form values that I need to update let's say
title from 1 to two so this title will be present in my updated book form data so I'll pass this updated book form data and remember we need to pass one more property which is new new means it will give you the updated book back okay so this will be our query that we need to do that's it if again once again we need to do the same thing so copy from here and after this we'll paste it and we'll do if this updated book is not found that means this book is not present with this ID else we're going to do ras do status of 200 do Json and we'll do a success as true now this time we'll send a message also that okay book updated successfully and also you're going to pass the data which will be our or updated book sorry update book no updated book this is the one we're having right yeah now this will update the book now let's check it all right so
now let's test it so we'll go there and let's create one more and then we'll do this one as update book by ID paste it and this will be a food request and this will be a update right and let's see we are passing the ID let's take the first product first book I'm going to copy the ID go there and we'll paste it now let's go to our add new book and here I to copy this let's go to update book by ID and let's go to body and select raw and I'll paste it here now remember we have the Fast book right so first let's go to our list of book so this first book added to I'll change this one to First book edited all updated okay and I'll make the year as 2023 remember this so here I'll go and I'll do first book updated and here I'm going to do author
I'll keep as my name only and I'll do this one as let's do 2020 now let's send this so book is now updated successfully first book updated we are getting we are getting 2020 let's go to list all books and let's send it and now you're getting first book updated here is 2020 so it's working fine now we have completed all of these now let's test one more thing step by step so let's go to add new book I'm going to add a new book added or something whatever so do new book added I'll do John do 2 and I'll do 20115 okay and now I'm going to send it so new book is now added let's go to list of books send it and I'm going to go to the last so it's now added let's copy this let's go to book details by ID and I'm going to pass it here send it so you're getting new book added now we'll go to the update book by ID and I'll pass it here and I'll change
this one to let's say whatever we'll do new book updated right we'll do new book updated and it was 2 20115 I'll do 20 2000 and author I'll change to s or my name I'm going to send it so now this is updated and now this is also updated and if I try to go to delete and let's I'll delete this so This Book Is Now deleted if you go there it should not be there send it so you're getting only two right awesome so now we have completed our Cloud uh Cloud application or simple project where you'll be able to create or add new product get all the product or get all the books get books by ID update books by ID and delete product or books by ID so now what will be our next step now next step we need to understand some of the things the first thing we are going to there are a couple of section we need to cover the first will be like authentication very very important how
to do register how to do login how to create token right all of this and then we are going to understand sorting how sorting works then we'll be having uh sex and on sockets so there are quite a few things so let's start uh step by step but for now your homework will be what you can do right don't use any front end let's say you are joining as a backend developer in a company so not be getting access to the front end more often right you need to play with your post M and your code why I'm telling it's very very important so create another project instead of using book change this one to a let's say e-commerce project some products and what you can do right go to this uh book model that we have created here instead of using title author and those things just add some more property here okay and then try to see if you're able to complete all of this and also check if you're able to test it or not using Postman once you are done then move to the next section all right so that that will be your homework and this is going to help you so now let's move on to the next part so now it's time to start one of the very important section in this
particular course and that will be to learn how we can Implement authentication in our nodejs application right so there are basically two parts when we are talking about authentication and I'm pretty sure if you have already work worked with any project so you know that authentication is the key part or one of the main features that you need to implement and it's very very important so first thing we have a authentication and then we have a authorizations right so let's quickly see uh what are the things that we are going to implement and also I'm not going to uh like uh spend more time on the explanation part but what I'm going to do right whatever things we are going to learn by coding we'll be learning all those concept and by doing it will be easy for you to understand those things so let's say we are talking about very simple uh web application right very very simple so how the flow will work so you go to any project any website let's say this one so this website will have this option right so you have a register form so let's uh let's say is your register form so here you need to give
your username your email and then your password correct and then you'll do a register so once you'll do a register means now this user is registered in your database so let's say we have our mongodb database here okay so this is our database so now how the flow will work right so whenever your user will be registered so now user will be redirect to the login page so if we are going to the login page right so what will happen we'll be able to read our username or let's say it can be email anything from our database so that we will get when the user will be registered and once we log in what will happen we will be able to go to let's say to the homepage or any other page now there are again two things let's say your website has two parts so there are let's say 10 pages right and five of them five of the pages are a public page public page means those pages no authentication will be required means any user without authentication or without login they can
access those pages but there are five pages that only authenticated user only can access for example let's say uh a billing page where user will be saving their credit card details so you can't allow every user to go and directly save right so you need to create that particular user information in your database or else someone will come and they will do something wrong so that is the reason this is very important so these five pages these five authentic authenticated pages that you'll be having how you'll identify so whenever user will be logged in with the user and the username or email and with their password so you'll be able to identify okay so this user is already registered okay so this is one part now the second part is we are talking about authorization so what exactly authorizations a role based authentication is so let's say your user has two roles right so one will be user and one will be admin now this admin can only access some specific pages that normal user cannot access right so here now if you see in both the cases like
normal user or admin user they both need to needs to login first right so login is mandatory so it's not like that if your admin user you no need to login login you need to do so this will be your first step so authentication you are doing second level of check will be your role based authentication as I already mentioned let's say these five pages that you are having out of which four are uh like four are related to your user and one there is one particular page which only admin user can access so how you're going to understand that if this user that logged in if this is admin user or not right so how we'll do it so we'll be storing some particular something like a role and this role will be either a user or it can be an admin so whenever we'll check that okay now the logged in user is a admin user so in that case that user can access this particular page right but if that user is not a admin user so normal normal user so what will happen we need to give some protection in this
particular page that okay you don't have permission to visit uh this page so you can't see this page or you can do something like this uh you need to first get your admin access then only you can access this page now that is not the point I'm just explaining the flow now what we are going to understand that how authentic works right and then how we are going to create cookies and then how we are going to handle role base authentication also so what we will be doing our flow will be something like this so we'll be having a register flow right and then any person can come and they can first register so in the register we'll be having a username we'll be having a email we will be having the password and also we'll be having a role Now by default the role will be always user right and then there will be another role that will be admin so once user will be registered they will go to the login flow so this will be our login flow now here again they needs to give their username or email or and their password so once user is logged in we are going to create a
cookie and we'll be storing that cookie now that cookie what that cookie does that cookie holds that user information that authenticated user information and using that cookie only you'll be able to understand whether the user is authenticated or not and if the user is authenticated then only they'll be able to go to this homepage so this homepage is a protected page so no user can access until unless they will login so first so this will be flow so first they need needs to register they'll go to the login page once they'll login they will go to the homepage and here there will be another special page that will be related to admin page now who can access this admin page only admin user so if a normal user try to access this page you will be showing something like you can't have access something like that so this will be be the overall thing that we are going to implement in this particular section now you might think that why I spend uh this much time explaining this very simple thing although this this is looking very horrible but I want to give you very basic idea because what what I mention right that the project that I'm creating that is for very beginner level
of uh students if you don't have any idea let's see if you worked with uh noes for some time and then you want to enhance your knowledge always always always you should start from Basics believe me or not these flows what we are going to learn it's very very very important like I will highly recommend don't skip the next three or 4 hours what about whatever things that we are going to learn in this particular section so now let's get started so what I have done right you can see that I already have a uh very uh simple folder nothing else so first we're going to create our basic uh package.json and we'll be installing all the uh packages that we needed so first let's do npm init and I'll do minus y right so this is now created and now what are the things that we need so first I'm going to install Express and also need mongus I think these two have already discussed that we don't need to explain this one what else we need we are also going to use our en EnV so this EnV will help us to read our environment
variables that will be having for this particular project all right so now let's install all of this and also we going to install our da dep dependency which will be a node mod so I think that also you have discussed in the previous section right so node modon will check your changes and you no need to every time you start your server to see the visible changes so I'm going to do npm installed node one save Dev okay now let's go back and also you can see that I have actually created one more uh phrase mongodb project so I think this is still in progress I don't know why this takes lot of time sometimes let's see okay I think this is still taking time so till this part is done let's go there and we need to do a couple of things right so the first thing I'm going to create one file here and that will be our main server.js file right so this will hold all the main uh our main root file you can say and now let's go to our package.json and now I'm going to
change this one to server and also will add our two scripts right sorry okay let's delete it I don't know how to delete this one okay let's skip it like this so now here I'm going to add our start script which will be what our server.js and also I'm going to add our da script which will be node server.
js okay so this part is done now let's go to our server.js and and we need our now remember we I already told you that we'll use this EnV right so I'm going to use the EnV and we'll read the config so that I'll keep at the top in the root file next we need Express right so we'll do require Express and I'm going to create our app so which will be let me ex do like this then it will be easy and I'm I'm going to invoke this Express all right after this I'm going to just listen so app.
listen so now let's go here and let's do step by step so first I'm go and create one EnV file and I'm going to keep the port as let's keep the port as 3,000 okay so now let's go there and I'm going to do that const Port will be process. env. port or else it will be 3,000 by default if you haven't created the EnV file so you can directly pass it like this but I highly recommend keep this practice it will be helpful because in uh very large companies how this works right so either we create a environment file or you'll read the file from CCM something like that so here okay we don't need to do this we'll pass the port and let's do a call back and I'll do console.log and I'll pass here that server is now listening to port and then I'll pass the port here save it all right so let's run this so
I'm going to do npm run Dev all right so server is now running and now let's see if the mongod database is created see it's still loading I don't know why okay let's wait for some time till this part is done then we are going to start our main flow so finally this is done after a long time I don't know why it took so much time so now let's go to connect and then we're going to click mongod DV for vs code I'm going to copy this now what will be the next step now we should do everything step by step right because we using environment variable so here I'm going to do a URI okay and here I'm going to give I'll paste it and then what we need to do we need to change this right 22024 now let's save it we'll go there and now we need to structure the project now in the previous section we have already
discussed right that we need to create our database we need to create models or we need to model our data that how we want to store our data in our database we need to create controllers we need to create helper methods then we going to create routes and at the we will'll be using those routes in our server.
js or whatever name that you'll be giving here doesn't matter so first I'm going to create our database folder here okay you can give this one also name as DV it's okay and I'm going to give db. JS and here we need to connect to our database first so now let's start so first we need our mongus right so we'll do const mongus will be require so we need mongus and then we're going to create const connect to DB this will be as sync method and what we need to pass we'll do a tri block we'll do a catch and here we are going to just log error so we do here mongodb connection failed right and then we'll exit the process we do process. exit with one all right so in the try we are going to do AIT and we'll do mongus do connect
and what we need to pass we need to pass process. env. URI remember this is the name that we have given and that's it and here I'm going to just log here that mongodb connected successfully okay that's it and then at the end we're going to do module dox exports and we'll pass our connect to DB so this will be our logic that we have needed now what will be our next step now why I'm repeating every time that what will be your next step because I want all of you to understand or right see again it's not like what I'm telling that you need to exactly follow the same I never say these kind of things if you watch my previous videos also I always uh tell you that please try to bring your own Innovative idea and try to create in your own way okay but you should do each and everything is step by step so because we have already created a mongod database we need to use that in our server so that will be our next step right so here what we'll do so we'll go
there and we'll do const and let's give this one connect to DB and this is reord and we need to go to database DB okay and then what we'll do simply we'll connect here so we'll call this connect to DV now let's expand this and I'm going to just save this let's see what what is happening mongodb is now connected successfully so our mongodb connection is now successful so what will be our next step now we need to let's go to this page once again so we'll start with our sorry we need to start with our register flow so what are the things that we will be having in our model so that will be the first thing now again this model that we'll be creating right this also you can create whatever you want to or whatever you like for example let's say I want to keep a user name field so this will be my username then I want to keep a email field right and then I'll be having a password field so think this one as like you are creating a front end application
right so here you'll be having this field now why I haven't created any front end app till now you might think right as I already mentioned every time it's very very important if you're going for a nodejs developer role in your company so there is a very less possibility that you can interact with your front right makes sense because as a backend developer you need to create your own modeling data modeling that what are the things you needed you can discuss with your other Engineers or your product man managers or whatever until unless you are a full stack developer then only you can check okay this all the things we are having in our design and based on that you'll can create now obviously you'll be having the access to your uh design that what are the what is the business requirement and based on that you can create your data modeling but the reason why I haven't created any UI here now because I want you to apply your own ID and based on that you created now what is the example why I'm telling it because let's say we are creating a username field here if you want you can remove this field completely right you can only keep email and password that is also fine so okay so this is username email
we be we'll be giving password and what other the things we'll be having we'll be having a role the role we are not going to specifically pass from our front end now if you go to any website any website you'll see see that there will be no role like you can select or something right in a real website so here we're going to pass a default role as user every time and for admin user what we'll do we go to our database and manually update one of the user as admin user now that is absolutely fine to do that mean normal big companies how this will work right so I I think I already mentioned this one multiple times that they have some CCM control things so in the CCM so it's a tool so there they can update the admin or super admin and based on that they can manage the role there are many many many different ways you can do that but we are going to follow this one for now so these all the things we be having so we'll be having a username we'll be having a email we'll be having a password and the role role will be default will be user so now let's go there and let's create our models folder right so I'm going to create models and here I'm going to give this one as user.js
so here what are the things we need so you only need here mongos this will be require mongus and I'm going to do const user schema so this will be new mongus do schema and here we need to pass right and also I want to pass a time stamp here and I'll make this one as true so now let's start with the first one so first I need a username so I'm going to to give a type which will be a string required I'm going to make this on as true that mean this field is required then I'm going to pass a unique property here now these all the properties and everything you can just play with the Mongo's documentation you basically able to understand all of these unique means like I want this
username uh to be unique let's say if there are two users and one user is giving username as a say n and the second user is giving the same username but this user is already registered and stored in our database so we not allow this user to give the same username because this San username is already exist so they this user has to give a different name so now San one now let's say there is a third user came and they given San one again now San one is also already stored so not allow this user to give the same username right so we'll keep this one as unique so unique will be true and I'll make a tream as also true so this is our first username field next we'll be having our email email also type will be string requir also this will be true definitely unique will be definitely true very very important and also we going to do a trim as true and let's give this one as also a lower
case because we want want the email in lower case so this is done now after this I'm going to have my password so password I'm going to just keep the type as string and required will be true that's it so now we have a username we have email and we have password next we'll be having a role property as I already mentioned and this I'm going to keep this on a stripe which will be string and I'm going to pass enum me I want to tell mongos that okay this user the whatever public will come to register in your website the enam can be only a user so it can be only a normal user or it can be a admin user now if you want you can also play with like let's say you want to add one more Super admin so you can add something like that but for now we'll be having these two role so basically telling that okay only allow something like that user so only allow user or admin roles that's
it so this is done and after this we will do a default property and what will be the default we already discussed default will be always user right because it is not possible that see 10,000 public is coming you'll make the 10,000 all the user as admin user right so that can be only one super admin or something like that so other will be always user so that is the reason we are keeping the default as a user I hope this will be pretty much clear right how we have created again if you want you can just change it based on your idea like if you want to add one more thing you can also do that after this we going to do module do exports and we'll do a mongus we have already discussed what we need to was we need to use model correct and then we need to give the collection name and that collection name will be stored so I want because we are creating a user so I'll give the name as a user as simple is that and always you should give a relevant name here like if you're creating user and if you're giving products doesn't make any
sense and I'll pass the user schema let's save it and this is done right so now we have created our server.js we have run or listening to the port we have created our DB connection we are calling this here and then we have created our first model which will be our user schema now what will be the next step so next step we need to start working on the register and the login functionality right so we'll be creating our main logic that how we are going to allow user to register in our uh website and then that information we are going to stored in our database so let's do that in the next part so first we'll start with our register endpoint right so in the register Point what we discuss that we'll be having a username we'll be having a email and let's say password now what will Happ if I giving a password 1 2 3 4 5 6 7 8 so that password we are not going to directly store in our database right so we need to has it or we need to store in encrypted form so that is the reason
we're going to use this most used package and that is called the bcrypt JS what this does you can see that it will create a Sol to protect against your Rainbow table attacks and how this will work so it is very very simple so think about a real website so when you're typing your web uh password and click on submit button what you'll do you'll pass that password and your email and your username information to your back end so that back end will receive that password and then we are going to call this bcrypt do salt method so you can see that there is a salt method that we are going to use which will store a has of that same password value in your database so whatever database you are using so let's say how we are going to do that first we need to go there and let's say I'm going to create one more folder now and that will be my controller okay and here I'm going to create let's give this one as Au controller.js and here first again uh as we already discussed in the previous
section that when you'll be creating any controller and any route right so you need to First think that what how many routes I needed and how many controllers I need to create because each and every route will hold some logic right that part also you discussed that instead of writing everything in the router file we we will separate that logic into a controller so that our code will be clean and it will be much more readable now it is absolutely not incorrect to write everything in the router file also it's absolutely fine so here what are the things that we needed so first we need a register endpoint right so need a register endpoint and also need a login endpoint not endpoint I'll do register controller and also I need login controller so let's start with these two so now I'm going to to C uh create a method so I'll do register user and all this will be async right so this will be async and this will give you your request response and here we are going to first use a try and we'll use a
cat let's log this error and here we're going to pass a status of 500 we'll do adjacent and here we're going to pass a success as false and message I'll do something wrong I'll do some error occurred please try again so this will be our first method second we'll be having a login controller login controller again if you go here we have a login page right will be having only email and let's having a password or also you can do as a username also and the reason why I'm telling is that if you go to model and if you see the username right you can see we are making this one as unique now if you are not making this one unique it's very very important to understand this concept that if your username is not unique and let's say there are two user already registered with a John username so in that case you
can't keep your username as input from your front end right so that means you will not understand when a John will log in that which John is it because both user have the same username so you need to first check that okay which of my field in my model is actually unique so in this case our username is also unique and our email is also unique so now it's up to you whatever you want to keep you can either keep your username here or also you can keep your email here but if your username is not unique so what you need to keep here you need to keep your email field I hope you're getting so that is the reason in some of the website I will not say some but most of the website will see that they will keep email as a field and password will be obviously common the reason is because email will be definitely a unique email uh like I'll give you another scenario right so email will be either let's say Google email or Microsoft email right so if you are creating a Google email and let's say you have already a John the gmail.com and if some other user is from some other country try to use the same username so Google will not allow right
so that is the reason when the you website will keep the email as a field here so they are pretty much sure that okay that email will be a unique field right so that is the reason in this case you can keep email but in our case we can either keep email or we can also keep our username so that is the reason we kept both as unique I'll go to O controller and I'm going to create my login controller now so const login user which will be async request response and here I'm going to just copy the same thing instead of rewriting so copy this and then I'm going to paste it here save it now what will be our next step now remember so after creating the controller definitely the controller logic is not done so what we need to create we need to create our routes correct so here we'll go there and then create one more folder and do routes and then I'm going to give Au routes now here we need
Express so we need require Express and what else we need so here we need to create our router remember so you'll do router which will be Express dot router and at the end we need to do always module do exports and this will be our router now I always always forget so that is the reason I'm writing first now here we need to create all our routes so all routes are related to user or let's do Au authentication and authorization so here we'll do router dot post right and here I'm going to give this one name as register because we're registering the user and now we need to get our register controller so we'll go there and I'll do const get it so first we need to go to our Au controller now
if you see right where we are not exporting this from this file from our controller so we need to export this we'll do module do exports and I'll do a login user and also the registered user okay let's put it here at the first save it so now let's go there and now I'm going to import it here so we do require controllers o controller so we need register user and the login user so now when we'll be calling our register endpoint we're going to call the register user controller and then I'm going to create one more right I hope you're already I'm pretty sure you'll be able to do this now so here I'm going to now do login and I'm going to pass my login user so till this part is done so so now is this flow is completed so I'm asking you no right so what will be our last step so created our database connection created models created controllers and created
routes and also map our routes to the controllers that we need to call now we need to go to our server.js and we need to use this router right there so go there and let's import it as a Au routes right and here we're going to do request and then I'll do routes and we'll go to Au routes and here now I'm going to use let's say I'll do app do use and here I'm going to use SL API SL O So this this is our main route for o and here what we need to was we need to was the O routes so what will happen we'll go to SL API SL and then slash register I'm I'm going to call this when I'm going to go to/ API sl/ login I'm going to call this login user all right so now the flow is completed and now we'll come back to the
controller section so we need to start our logic creation right so how we are going to register a user okay so while registering the user first thing what we need to do first we need to get all the information that we needed from our front end so in the front end user will be typing username they'll be typing their email and they'll be typing their password and they'll click on the submit button and this I'm going to pass in my back end so in this back end in this controller how we are going to get it so we'll be getting our request. body remember so this part actually we have already discussed so first let's do like this we'll do first extract user information from our request body right so from our request body and here I'm going to do const and I'll get what so do request do body now very very very very very important while I'm repeating this the reason is because now you need to go to
your uh schema and you need to check the naming that what kind of fields that you need here username you need email you need so you see that n is small so these things are very very important models it will not map it to your database so here we need a username what else we receive we'll receive a email and also receive a password so these three things we're going to receive from our request.
body so why uh we haven't take our role for now so we can also take our role so let's say we have this we'll pass this role or else it will be always takeen def default as a user so that is fine but let's for now we'll pass this on as a role because I just want to show you that how we are storing this in our database that is very important later we can change it it's no issue so here we'll be passing our role username email and password that I'll be getting from request. body so this is first thing second thing what we need to check is that first we need to check if the user is already exist in our database very very important right because again I already mentioned that if the user is giving a same username or email that is already stored in our database so in that case it will be very uh it will not be unique right so we need to check it so now I'm going to create a variable and I'll do a check existing user so do check
existing user so how we are going to check it so we do AIT and now we need our model here so now I'm going to import const user and this will be require so we'll go to our models and then we'll go our user so this will give me my user model and here I'm going to do a user remember this method we have learned that find one and here I'm going to pass a or method now what this or will do right so this or will check we are going to check either if this username is already exist or email is already exist with the same email then we can basically tell user that okay this email is already exist in our database so you need to try with a different email something like that so here in the or we are going to pass what so pass our username see it will automatically take see it's taking usern name right and give comma and then I'm
going to do email see if it will take automatic email so that means we are checking that if this username or the email is already exist so in that case this so if this existing sorry check existing user is true so we can simply do a return and we'll do rise. status and I'll do a 400 and I'll do a Json I'll pass a success as false and I'll do a message that user is already exits with uh will do exist either with same username or same email please try with a different username or email okay so this I'm going to return
if the user is already exist if user is doesn't exist what will be our next step so now you need to think here okay okay so now we have come to this step so now we need to do nothing just store all of this in our database but that is not the case right we are going to has this password so there this bpj will comes into pictur so now let's copy this and I'm going to open another terminal and I'll just paste it here so this is already installed very fast now we'll go there and then I need this so do bcrypt and I'll do require and I need bcrypt JS so once this check is done so I'm going to now do has the as user password so here I'm going to do a const and I'll create a salt and here I'll do
AIT we'll call the bcrypt and we'll call the J salt method so here we need to pass a number so you can see that number to use and if you don't pass anything it will defaults to 10 now we're going to pass a 10 here and then I'm going to do const and I'll Do Hast okay let's do H password and this will be AIT and I'll use the bcrypt do has and then here you need to pass what you need to pass the string and you need to then pass the salt so salt we have already created but can you guess what will be our string so this string will be the user input password user input password means if you go here let's see I'm like explaining very very simple way that is the reason because if you're complete beginner you'll be able to understand so user input password means what this user has pass typed in the password field in
the front end let's say 1 2 3 4 whatever and this password is which password this password field right that you are getting from request. body so you need to pass this password here okay so this is done so now your has password is created so now you can create a new user so now create a new user and Save in your database right and now I'm going to do a const let's do a new created user and I'm going to do a new and I'll call our user model okay and here we are going to pass what are the things we need to pass first we need to pass the username we need to pass the email we need to pass the password but here there is a trick and we need to pass the rule so first we'll start with the username so I'll pass username I'll pass my email and then we need to pass our
password right now if you notice one thing here I want to mention another thing I know these things I'm taking so much time to explanation but it's very important here you need to pass a password right so you'll pass a password but if you pass this password which password it will take can you guess it will take this password so this password is not the hash password right so what which password you need to pass you need to pass the hash password so I'm going to pass the has password Here I hope you're getting and then in the role so we'll be getting the role if we are getting the role from our let's say body so it will take from there or else will pass the default as user okay so now newly created user instance is done and now we'll do save right so we have it so do newly created user do save now again if you want you can also use that create method also that we discussed so in that case you don't need
to use the save but both the things are okay and after this we are going to do something like this so we'll do a r let's do if newly created user is true so we'll do a uh race do status of 2011. Json and here we'll simply pass a success as true and message I'm going to do a user registered successfully else we'll copy this and then we'll pass it here so we'll do 400 we'll do a false and we'll do unable to register user unable to register user please try again all right so this part is done so now we need to just test it right so
let's do this one in the next part we'll just run our project or create a new collection in our Postman and then we first we'll start testing our register user and we'll see that if uh you we are able to save username email and also the has password in our database so we are going to check this one in the next part all right so let's start testing this in our post one right but before that we need to do one more last step and that is if you see that whatever endpoint that we are using we are getting all the information from our request. body right so we need to use our Express middleware that will pass our Json uh request bodies remember we have used in the previous part so here I'm going to use my middle words so I'll do middle words and I'll do app. use and here I'm going to pass Express and then we are going to use our Json mle uh Json middleware right so now let's save it now let's go to our Postman and then I'm going to create one new collection we'll do blank collection and let's give this one name
as nodejs o okay now here I'm going to create our first request and I'm going to give register and user now let's go there and let's copy any URL from here for now now another thing I will show you that how you can create environment variables here right and based on that you can use instead of using this local L 3,000 every time so you can use variable also so register an user will be a post correct and then I'm going to paste it so this will be/ API SL SL register and here we're going to pass go to our body and go to Raw we'll keep this one as Json and I'm going to pass our username right so first username and I'll give my name I'll use email that I'll give this email suum gmail.com then we need to pass our password which I'll give just 1 2 3 4 5
6 7 8 and also I'm going to give a role which will be a user so these all the things we needed correct so now let's do do a send request so awesome so you're getting user register successfully but this is not the point I want to show you I'll go there and let's go to our browse collection and let's see in what format or in which format this user is getting saved here so if you notice one thing right that we are getting this is fine like username or email everything but password is getting saved in this has format right so this is working fine and the role is now user so now when the user registration is successful this part so we need to go to the login flow now what will happen user can either give this username or the email in this field so let's see if we are keep keeping this as a username so they needs to give username if we are keeping email then needs to give email and then they will give their password
if that password is matching with this password that is saved that means you'll understand okay this is the valid user that's try to access our page or homepage or our application or website so then we'll allow our user so but how we are going to authenticate the user so for that whenever user will give their email and password right so that means we will create a token and that token will hold that user information now what I mean by hold user information means the token that will be creating that will will keep the usern name and the email in that particular token and that token will definitely will be valid for some minutes let's say if any user is coming to your website and then they try to log in so we'll keep the token as valid for let's say 15 minutes and after that the token will expect something like that but because we not going to much advanced level in this particular video I will 100% definitely going to create a second part of this node course where there will be all the advance level of things that we are going to
learn but I think because this will be very very lendy already so that is the reason I'll try to keep things from basic to intermediate level or medium level okay so what are the things next we are going to learn first we learn that how we can create our uh login controller how we can create our token using Json web token how we are going to store that token in our cookie and then we are going to log that user particular user and after this only we're going to understand that route right authentication rout authorization route that we have discussed that only admin user can access admin route and the other user can access the user route something like that so let's start with first the login controller in the next section and after this we're going to do quite a few things so now we'll start working on the login controller functionality right but before that I want to show you one more thing and that is I just created one more user and remember we have given this condition right so if you try to register with the same username that is already exist so in that case you will get some error right so let's uh try to uh replicate that scenario so you can see that I have
this username and now I'm going to change this role to from user to admin and let's say I'll do okay first I need to run this so let me just run the server so do npm run Dev all right and now I'll go there and let's send it and let's see what we getting so you can see that we getting user is already exist with either same username or email so please uh try with a different username or email now I'm going to do here so let's give a two and I'm going to give a two here and this time I'm going to make the role as admin for this particular user and let's do a send now you can see that user is now registered successfully so this is I just want to show you quickly so if I refresh this page you'll be getting now three user because one user I just uh added in between so that is the reason so these two are the users and then we have one uh user which is the admin user so now this part is done now let's quickly see how we are going to implement our login controller functionality so now let's minimize this
and I'll go to this login controller and let's first try to understand that what are the things we need to do now as you have already remembered that while creating our model we have kept our username and email both as unique so while login we can either give user to option uh to login as username and password or you can also give as email password right so in this case we're going to use username but it doesn't make any difference if your username field is not unique in that case you need to keep email and password okay so here whenever user will be login so normally what will be the flow right we have discuss multiple times again I'm going to repeat one more time so in your UI side you'll be having a email field or username field whatever and then you'll be having a mandatory password filter right and then there will be a button and on click of this button you are going to pass these two information to your back end and from where we'll be getting it so we'll be getting from our request. body so that is the first step so first we're going to extract our username and also we going to get our password from where so we'll do request.
body okay and once you'll get this what will be our next step so next step you need to check whether this username is already exist in our database or not as simple as that for example let's say if I go there and I try to loog log in with suum five but you see there is no user with suum f so what will happen if the user is doesn't exist so that means they will not able to login in your website right so they needs to register first so first we need to check this so here we are going to check that first find if the current user is exists in database or not so we'll do const and we'll do user and this will be AIT and here we're going to use user model and remember we have this method which is called find one and here we are going to pass what we are going to pass this username so I'm going to pass this username so that means what it will check it will check that if this user is already exist with this username is not
with the username or not so now if this user is doesn't exist in your database so simply return so what you're going to return here so return r. status of 400. Json we do success as for false definitely and message we going to do invalid username or password something like that okay let's give invalid username because if this user is doesn't exist okay it's so fine or else better will be you can give also invalid credentials I think that will be better now this is the first step now once this is done what will be your next step so these things you need to understand step by step so first you check that okay if my user is exist in my database or not then you need to check the user is entering a password in your front end right so let's say if you go here this user is now currently hash password sorry not user the password is stored as a hash password but if you decrypt this right
so what you'll get you'll get 1 2 3 4 5 6 7 8 now now currently it is in encrypted form but when user will be log in from your front end they will not type this right definitely they are going to type 1 2 3 4 5 6 7 8 that means whatever user is typing while logging you need to compare both the users so the first one will be the user is typing that password with the password that is stored in your database if both are getting matched so that means your password is correct or user whatever password they're entering in their form that is correct so that means this user is a valid user so now we are going to check that if the password is correct or not so here we're going to do const is let's do password match so this will be have it so L Crypt dot compare so there is a method so this will give you the compare that you want to compare so we have a string that we
need to pass and the has so what will be the string here so this string will be this password that user is typing in their front end so you're going to pass a password here and then what will be the hash password hash password here you need to give this hash this is nothing but the password that is stored in your database now you might think that okay now how we are going to get the password from the database so that is the reason you can see that we are getting the current user so what this user will give this user. password is what this user. password is nothing but the one that is stored in your database correct so here we are going to check if this password is matching with user dot see I I'll do password see we getting password right so both are getting matched so in that case this is a valid user if this is false in any scenario that means your uh credentials are invalid so here also again we're going to return the same thing let's copy this and return it once this is done now coming to the main thing now here what
you need to do very very very important so now whatever we are going to do right will we are going to create a token so what token we going to create so whatever username and password that user have entered based on that creden Sals if the user have given correct creden Sals so we will be creating a token based on that user information so from where we'll be getting the user information this user will hold all the information so it will hold the ID which is the user ID it will hold the usern name email password roll and everything right so in that case we need to create a token so what that token we are going to use we are going to use the token as a beer token so that is called a term that you called as beer so it's called b a r beer token what this beerer uh means if you see the word right it means a beer so what it bear it bear the uh information or the caran cells of that particular logged in users and that we are going to store in a token right now using that token we can do various things right so there are lot of advanced topics and these to if I start
uh explaining these things right it will be like uh one or two hours long so what you can do first of all we can store that in our cookie or else what you can do you can pass that token back to your front end and then in the front end you can store it in your session storage and let's say there is a API that you need to call and in that API you need to pass that uh that token as a b token so what you will do either if you are storing that token in cookie so you'll get that from cookie and then you will pass it or else if you're storing in your session so what you are going to do you'll simply pass get the token from your session storage and pass it in your API right something like that but here first we need to create the token so let's say how we are going to create the token so now because the password entered is correct so we'll go to the next steps we need to create our token so create user token so for this one we're going to use this Json web token this is uh like one of the most used pack uh packages that we usually use so here you can see that if you see the users right so we will use this JWT so this is the S form do
sign method so here you need to pass this payload and this is very very important what this payload is nothing but this payload will be the payload of this user so this user information right and here you can pass whatever information you need to pass then it will take a secret private key now if you search in Google right so you'll get various options to create a JWT token now you can give whatever value you want it's always better to give some good secret key here and and then there is some options or call back you can pass here if you see right in the synon way it will return the Json web Tok as a string and this string you can again pass back to your front end and then you can do something else let's say as I already mentioned you can store in your cookie or in your uh session storage whatever first we need to install this so let's go and copy this and then I'm going to install it here okay so this is done now I'm going to first import it here so let's do const JWT and this will require so you need Json web token okay
now we are going to create our access token so we do const and we'll do access token so we'll use this JWT DOT sign as I already mentioned now here you need to pass the user information so what are the things we are going to pass here so we will be passing all the user related information so first I'll pass a user ID so what this user ID will be this user ID will be this current user right it's very very important this part so here you need to get the user and if I do Dot and you'll see that all the information you'll be getting if I do ID see you're getting this ID so this ID is nothing but the user ID that you're getting from the mongod DP then I'm also going to store the username here so this will be user do username correct and then I'm going to also store the role which will be user. roll now if you notice I'm not storing the password here right so it's only storing the username user uh ID and the role what will happen right this will create access token in
encrypted form or this Json web token and in that token that token will bear or hold all this information this user ID username and uh role so if you encrypt that it will give you a Json web token if you again decrypt it so you'll be getting all this information now here as I already mentioned if I overr right you'll see that it will also take a JWT secret or private key now what I'll do let's go to our EnV for now I'm going to pass here JWT secret key now again I'm I am passing here this the same now you can give whatever value you like okay so now here we'll go and then I'll pass here process EnV dot we have JWT secret key and after this we need to pass a xare value like we can pass some options right so we will tell that okay this token will be valid for let's say 15
minutes or 60 60 Minutes or 30 minutes whatever you can pass so I'm going to pass a expires and I'm going to pass it 15 minutes so now this will create a access token now what we are going to do right after this let's do something like this so here we don't have any other steps uh now I'm going to just simply do ras do status of 200 we'll do Json we do a success as two and I'll do message as logged in successful and I'm going to pass this uh let's do this access token let's pass this access token so I'm passing back this access token so let's think about this so you have a front end and you are passing back this access token to your front end now again I I will explain one more thing that here we can also set it in our cookie but for now first we need to understand the flow right and we need to check if it is working or not as this is for complete beginners so now let's
recap one more time so you're getting the field from our front end now again I'm mentioning this username can be Emil it's up to you whatever you want to use find the current user if the user is not present return invalid creden Sals or invalid users or user doesn't exist whatever right here let's return user doesn't exist right and after this we are going to why this is coming okay let's do like this so now we are checking that if the password is correct or not if not then again we're going to return invalid credentials this is very important and then we're going to create our token and we're returning the token back now let's save it so now you're already logging and everything passing and in the Au routes you already have a login route so now let's go to our Postman and let's create one more request I'll do login and user so this will be a post and let's copy this
and this will be slash login we'll go to body we go to raw and I'm going to give the username so I'm going to give the username of mine so if you see right here we are having this username and remember what was the password so the password was 1 2 3 4 5 6 7 8 okay now let's do send so we are getting success true message is now logged in successful and you are getting access token here now this access token will hold all the information that we are passing here or we are storing in our this token so this this token that is generated there it will hold this user ID it will hold the usern name and the role of that particular user so now you are a logged in user so your login is successful so what will be the next step now next couple of things will be very very important the first thing is that remember we told you right that there
there will be two scenarios if you are a normal user and you are try to log in so you'll be able to go to certain pages not all the pages but if you are admin user then only you'll be able to visit other Pages as well as the admin pages so we need to create some kind of authorization or role based authentication right so that we are going to show in the next part so what we need to do for that we are going to create a middleware and that middleware simply check what it will check so it will check that if the current user is first of all it it's authenticated user or not that means if the user is logged in or not and after that we are going to verify the token right so this token should return this information as I already told you multiple times and once this is done then we're going to go to the next logic or next check which will be that if the user has admin access or not if yes then only they'll be able to get or access the admin Pages or else not so this part we going to do in the next section all right everyone so now let's do one thing right so as I already
mentioned that we need to create two more routes so one will be our home route and second one will be our admin route so let's go there and I'll go to my Au routes that we are having right so let's create two more routes I'm going to create home routes and also I'm going to create one more which will be admin routes.
js now in these home routes the first I'll get uh Express so do require Express and after this we are going to do like this we'll do router. gate so here I'm going to give let's say this will be go to the slome route and after this I'm going to Simply take my call back so here only I'm doing the logic because this will be pretty simple and here I'm going to do a raise do just and let's say you want to pass message that welcome to the homepage okay and after this I'm going to just do a module do exports and this will be my router but I think we need to create the router that we have haven't created so here I'm going to do const router this will be express. router
all right so this will be R.G sorry about that I didn't check notice that actually so first we created the express and then we created our router so now we'll go to the Home Route and then we'll be showing this welcome to homepage save it so now let's go to our server.
js and I'm going to now copy this and let's create one more this will be my home routes and we need to go to our slash home routes okay now here I'm going to just do let's do API SL home I think we already using home there so we need to change something there so I'm going to do a home routes and let's go to home routes and here I'm going to do SL user info something like that or let's do a welcome welcome route okay so this will now go to/ API slome and then slash welcome so this will get triggered so now let's go there I'm going to copy this and now I'll create one more request and let's do check welcome route so this will be/ API slome SL welcome and this will be a get
and I'm going to just send it here so you're getting welcome to homepage right now what we need to check that if the user is not logged in then also you'll be able to now access this page right so that I'm going to show you so what we need to do here if user is not authenticated so I'm repeating these things again and again in that case we need to someh protect this route so you need to show like okay you can't access this page because you are not currently logged in so how we are going to do that what will be the logic or concept that we need to apply now remember we have the concept of middleware right that middleware can run on every request if you're creating that midle in such a way that and then it will trigger the next function and then it will go to the next call back or next function it will call and automatically this logic will be getting triggered so what we are going to do how we are going to protect this route with a middle we so how this logic will work right so if you see here right in this router. gate here we can pass multiple handlers see this is actually is a spread they're spreading the handlers so you can pass multiple handlers let's say Handler one then
Handler two and then this last Handler will get run so what will happen let's say this Handler one is a middleware one this Handler two is a middleware two so what you are telling that okay first you go to this route then check if this Handler one is successful or not right then if it is successful then only this Handler two will be getting called if it is successful then this will be getting called something like that if something is breaking failing here in this Handler one so not not be able to get the response from this homepage right so this is what what we going to do so we going to protect this route with a o middleware and that middleware will check if the user is currently logged in user or not if not so they will be getting a error message like you currently can't access this page because you are currently not logged in but if the user is already logged in so in that case we are going to Simply uh return this welcome message because you are already locked in so you'll be able to see this homepage so let's quickly create that middle word step by step and then then we are going to use that
middleware in this particular Home Route so let's do that in the next section I'll just quickly remove this all right so let's quickly create the middleware so I'm going to create one more folder here and let's give this one as middleware and I'm going to do here o middleware dot JS so this will be a simple function so I'm going to give this on name as const authentication or let's do this on o middleware only so this will be as uh sorry this will be simple function here we're going to do request response and then definitely you need to call the next method here so we get the next and simply for now I'm going to just do console.log or middleware is called right but it will work no right so you need to pass this next method so now I'm going to Simply just do module do exports and I'll pass this off
middleware that's it for now now we'll go to our home routes and we'll get this o middleware so I'm going to do con o middleware and this will be recare so we'll go to our middleware and then or middleware now see what I'm going to do right for now we don't have any logic but I'm going to pass this off middleware as a Handler here in Middle and I'm going to just save this normally and now let's go there and let's quickly send it so getting welcome to homepage but that is not the thing I'll go to my note here let's go down see off medware is getting called so every time every time we'll just uh call this or go to this route this Au Med will be getting called now see what will happen right when you are creating a front end or let's say you back end developer or some front end guys are passing so they will be passing this token that we have created while logged in as a headers so let they'll be passing as a bared token right and that
token you will be receiving and you going to check that okay if that token is a valid token or not if it is not that means what the user is not authenticated as simple as that if the token is authenticated or sorry not authenticated if the token is valid so then this middle will be a success so it will come to this Handler and then you'll be able to go to the homepage now I hope this role based authentication will be clear not Ro based means how the main authentication or the route protection will work this is not a r Bas authentication definitely so that we're going to do in the next part but this is how you are protecting a particular route using a middleware now we are going to go to middleware and then we are going to pass uh start working on the logic so what first thing we need to do here first we need to get our header so we'll get our Au header so look const or header so how we'll get it so in this request you remember header is one of the properties so if you go here right and if you see there is a headers and here you'll be getting this all the properties like see there is a
authorization here so this request. headers of the authorization will give you the token that you'll be passing if you go to authorization right and there is a bearer token see this token we're going to pass so now I'll simply go there and I'll do here request do headers and I need the authorization property so do authorization okay and now I'll do nothing simply I'm going to log this so because we need to do step by step because I know some for some people this can be tricky so now let's save it let's go there now I'll go here and let's go to login and user I'll copy this token for now and I'm going to pass it in my BR token so I'll go to be a token here and then I'm going to pass it here see it's already there okay whatever sorry I think it's not copied so copy this and I'm going to just pass it
here now let's send it and I'm going to go here you can see that what you're getting very very very important you're getting a b error and there is a small space right right and then you're getting the token so now to get the token what you need to do you need to split it right so that is the reason so I showed you this t Okay from where this is coming so now we'll simply get the token so do token so this will be our o header right so this Au header and and Au header do split and this split we need to split with what we need to split with this space so do space and then I'm going to take the first element which will be this token right and this token is what it will hold all the information of that particular user now if this token is not present so what will happen so we do not equals to token that means user is an authenticated user so return return a response. status of 41 then we going to do Json and I'm
going to do a success will be what it will be false and message I'll so like access denied no token provided please login to continue something like that this is fine so now we'll save this and see what will happen if I go here right and I'm going to just remove this send it see what is coming right access denied so it will not come there because see why this is happening because you see you are immediately returning from here returning right so it will never call that homepage route so you're protecting this route like this so now till this part I think this will be clear so once this is done now we need to do what can you guess so you need to now decode this token decode means to get the user
information so user information we'll be getting so if we go to controller right this will hold all this information the token I already mentioned previously so now we take a tri block we'll take a catch and here I'm going to take a error let's copy this and I'm going to return a 500 and we return do something like this same in the uh Tri block we need to decode it so for this one we're going to use our JWT so we do JWT which will be reare and this will be Json web token and we'll go there and we'll do const extract token or let's do decoded token and here we're going to do JWT and this will give you this verify method and using this verify method you'll be able to check if the token is valid or not so
here you can see that what you need to pass you need to pass the token which token this token you are getting here from this part right that we have discussed so this will be our token and then you need to pass the key the secret key and secret key remember we have used this process do EnV dot let me check what was the name so go there and let's copy this JWT secret key and this secret key you need to pass here so now this will automatically give you the decoded token info if the token is is a valid token so here I'm going to just log this okay and then what I'll do right in my request I'm going to add this as a user info so I'll do request. user info and I'll pass this decoded token info because this decoded token info will hold this information user ID user name and role correct and now what will be the next step can you guess please pause and try to find now we need to call the next method here not there so now we
need to call the next method so what next method will do so go there and then now it will call this Handler because your au me delivery is now successful so it will go to this Handler so now let's save it now first we need to check what is happening here right so we'll go there and let's try to pass the token okay let's I'll just log in one more time so it will generate one more token let's copy this and I'll pass it here send it so now we'll go there and see what you're getting see user ID username roll and these two are provided but we need to focus on these things so user ID you're able to get from your the user ID that you stored while creating the token in the Au controller same for username and user R see how simple is is this right so now we go to Au routes sorry home routes and here I need that user information so how I'll get it see in the request user info I'm passing this right but you might think that okay
why we need that user info see this is a very simple project right in a real project when you'll be start practicing these things or in a company you're working you need to pass this information back to your front end let's say so front end needs to render the user information in the UI so you need to pass it right so in that case what we'll do so simply get your username your user ID and also what is the name I'm not able to recollect user ID and also the role and this will be getting from request do user info now what is user info user info is this user info that you're are calling right and after this this raise do we are showing welcome to homepage and then I'll pass a user and then I'll pass this let's I'll pass this ID which will be my user ID then I'll pass my username and also I'll pass my role so these three things I'll pass now let's save it now let's go there and let's try to send one more
time see what you got get it right so now this is working fine so if you go to login user I'll do two and then I'm going to send it one more time I got one token I'll copy this now again I'm repeating this token we can with we need to save in our variables and then we can use those variables but first we need to check it is working or not now if I send it what will happen because that is a admin user we should be getting the role as admin this username will be suum 2 and the ID will be related to that user send it see I hope this will clear the most of the things like how the flow works right so now you're able to pass the BR token and using that token you're able to understand that okay the user is now authenticated if the user is then only are going to the homepage right if I remove this right let's remove this send it so you'll not be able to access also you can try one more thing right okay let's do one thing I'll
go there Au controller and I'm going to make this one as let's say let's do a 01 minute or let's do 1 minute so I'm going to create a 1 minute of expired token so I'll go there login user user and I'm going to now send it so it will create now this token will be valid for 1 minute I'll copy this and let send it here so we getting uh this suum 2 and the admin that is correct but we need to try it one more time after 1 minute and we need to check if it is working or not okay now in the meantime we can do one thing and that will be so you need to go to our admin route now so in the admin route again we need to create the simple logic so first we'll start with the simple simple one so first I'll need my Express so this will be require Express and after this I'm going to create the
router so this will be Express do router and here I'm going to Simply for now do router doget so this will be welcome only I'll give and then I'm going to pass the request response and I'll do r. status let's just send it Json and I'm going to pass here message and I'll do welcome to the admin page all right so now I'm going to just do module.
exports and this will be my router save this so now let let's go there first first I'm going to send it one again see what happened so this token is now actually not working right so this token is now actually expired so that is the reason you are getting this but if I go there and send it one more time and let's now copy this and I'll pass it send it so now you're getting so this is the only part I want to show you but I'll now go to my o controller and I'll change this on to 30 minutes for now but now let's go to our admin route and this admin route we have already created so we need to now use this in my server.js correct so I'm going to copy this and I'm going to do this one as admin routes so this will be admin routes and here I'm going to do app.use this will be SL
admin and these will be my admin routes so now let's go there and tast it so we'll do add request so we'll do admin check admin route check admin welcome route okay logic and then I'm going to pass it here this will be SL admin SL welcome and I'm going to Simply send it so getting welcome to admin out that is fine but because we haven't protected right now this admin routes okay why it is coming like that let me check one more thing quickly okay we are creating this I think this is fine now what we need to do we need to give two layers of protection now why you might think the first thing will be in the admin route first you need to check if the user is authenticated or not and how we are going to check it that is pretty simple
we just need to use this o middleware here we just need to pass it so go there so now I'm going to just copy this and I'm going to just pass it here and then simply pass this as a Handler now I'm pretty sure I don't have to explain also so you're getting one layer of protection here so first check if it is uh valid or not and then only based on this you are going to uh go to the admin note if you now go there and let's try to send it see what will happen you're not able to access this because you haven't passed any be token here so now I'm going to log there and then here I'm going to having my if you notice right this is my admin admin username but now I'm going to do going to use my normal user and I'm going to send it and create one token now remember this point that I just explained so I'm going to copy this and go here now I'm going to select BR token and I'm going to just pass it here now definitely it will work we're getting welcome to admin route but now the trick now the role base
authentication will come so here you can see that normal user also able to access the admin route but that is not the case right so we need to give one layer of Extra Protection here so what we'll do right for now I'm going to just create here so we'll do we'll create one middleware or or let's do one thing right well let's go there and I'm going to create one more middle here I'll do admin middleware do JS so here we are going to simply just do uh let's create const is admin user so this will be request response and next now here we simply needs to check that if the current user role is not admin user then only we're going to return an error so look if this request. user. roll if this is not equal to equal to admin so we'll simply read raise. status of
43 and we'll do a Json of success will be false and message will be access denied admin rights required so this is the first thing if this is correct then we'll simply call what we're going to call the next that's it and now I'm going to just do a module. exports so module. exports now these points I'm not now explaining because we've already done multiple times so here I'm going to do is admin user so now let's save this now I know in one point you will be confused that also I'm going to explain so go to admin routes now I'm going to first get it so con admin middleware and this will be reer so let's go to mle Ware and admin middleware now I'm going to pass this admin middleware as a Extra Protection here so I'm giving this one if you see
the sequential way right so here I'm calling first a middleware and then admin midle now this will be clear that from where you'll be getting this request. user can you guess sorry I think I missed something this will be request. user info because we are passing request.
user info from our middleware sorry so this will be request. user info right so because we are calling o middleware first so Au middleware will call the next method and in the request we'll be having the user info right so that is the reason you're able to get this user info from this Au middleware and after this we calling this admin middleware now let's save it let's go there and try to send one more time see what happened nice right so now you are actually protected by two middleware so first one is checking if the user is authenticated or not second one is checking if the user has admin rights or not so this user is a normal user token so you don't have the admin rights so it will not work now I'll go to login and user I'll give suum 2 and I'll send it and I'm going to copy this access token and I'm going to pass it here now let's see see awesome right so now you're able to see the admin page so this is the
complete flow of how your registration and login Works how you can create token using JWT token how you can use bpjs so to has your password to compare both the passwords how you can create o middleware how you can protect route using this logic and also how you can use multiple handlers and based on that you can create role based authentication so these all part is now completed so now what will be on next step Next Step I'll give you one simple task if you worked with any UI framework it has not has to be only like react like everyone is react react like that it's not nothing like that it can be JavaScript it can be jqu it can be angular view SW whatever you want to use try to create a very simple project and then try to communicate now I will create one simple part where I'm going to show you that how you can connect your front end with back end but I'm pretty sure that you will be knowing this part if you have some idea on the front end because it is not that much difficult right so my
homework to all of you will be create one simple register page create one simple login page and then try to implement this logic with your front end right and then see if you're able to protect this route or not because this is not a front-end course if you want to know this logic I already have a react full course you can check there so that is the reason I'm focusing Moree and backend but these points are very very important and these you'll not able to understand only when you'll be practicing all this right so now this basic authentication part is done so next we will be moving to another very very important section and that is how to work with file upload so we're going to implement image upload we will be using multer and cloud inary and we will be using this project only and you may ask me why the reason is because in this one we have a role Bas authentication right so what we going to do normal user can only get the list of images so they can only see the images only admin user can upload an image I hope you're getting so that is a role base right so that we are going to implement from the
next section all right everyone so now it's time to implement file upload uh functionality right so for this one we are going to use two of the most used packages or libraries you can say the first one is called multer and the second one to upload and store our images we are going to use cloud inary right so what this cloudinary does is so we are going to use this uh cloudinary node SDK so it allows simply uh to integrate your application with cloudin and uh in this way we are going to upload all the images or videos whatever assets you are having in your application and what this MTA does so this is simply a node just middleware for handling multi part or form data right which is mainly used for uploading files so we're going to sa with a practical example and for this one we will be using that example only that for a normal user whenever they were logged in they'll be able to fetch the list of images but they can't upload it only admin user can upload an image now if you see right currently I logged in with the admin user so admin user can access this admin route okay so first we need
to understand that how we are going to form our uh this image upload model so whenever you will be working with any upload functionality always always I'm mentioning this point is very very important you need to first uh take some time and first you need to decide that what are the properties that you will be having in that file upload or image upload or video upload schema so in this case we will be having a image URL so what the flow will be like this so for example let's say you having a front end and in the front end you'll be having something like upload image right so this is the how normal process will work so we'll click on upload image you'll select a image and then we are going to call our cloudinary so Cloud inary will be integrated in our back end so this will give us some ID and everything so that we need to configure so once the image or video or whatever asset that you'll be having that will be uploaded in cloudinary cloudinary will give a public ID or a specific ID for that asset right or you can say that one as
asset ID and that asset ID and also cloudin is going to give a URL so let's say we uploading an image so that URL we are going to store in our mongodb right so this is the whole flow so first you select something in your front end right you'll upload that to cloudinary cloudinary will give you the image URL or uploaded URL and the public ID which is nothing but your asset ID and that you are going to store in your mongodb right so this is the whole flow so first we'll go to our vs code let's go to our models and I'm going to create a image. JS file all right now I'll just close everything else so first we need to decide once again that what are the things we'll be having in our schema right so first I'll do const and I need Mong so I'll do require and I need mongus here and then I'm going to take const and let's do this one as image schema so this will be new mongus do schema and here we will be having a URL the first
thing now what will be this URL this URL will be your image URL that will we are going to upload in our cloud in area and that we are going to store back to our mongod so you uh this URL will be a type of string and and this required will be true means this is a mandatory field that we need to pass and after this we also will be having our public ID now this public ID for now it will be little confusing but we are going to see what exactly this public ID is right so for now I'm going to do this one as public ID okay so this also will be a type of string and also I think we okay this is not required so this will be type of string and for this one also I'm going to do requir as true and after this we are going to do a uploaded by means which user is currently uploading this image so here I'm going to use mongus schema and I'm going to use the types and I'll use the ID or object ID and here I'm going to refer our user model now this
part will not be able to understand but don't worry because we will be discussing this advanc concept of mongos and mongod in the next section so here what we doing simply we are referring the user that which user is currently uploading that particular image and that we are going to store in this uploaded by this also we going to keep as required will be true all right and after this we need to give our time stamp as true so this will be time stamp will be true okay and after this we'll just do mongos do model and I'm going to give the collection name as image and I'm going to store my image schema so now this part is done so we have created the image now we know that okay what are the things we need to uh save while uploading an image but now comes the second thing first we need to upload that image to cloud in but we don't know anything how to use
cloudinary correct so first let's go there so this is the website you need to go and now definitely you can simply login with your Google so I'm going to just do that so let's click your login let's do login with Google I'll select this continue so it will go to your uh cloudinary console so where you'll be able to see all your credentials so what are the credentials I mean is basically that you need all the IDS and everything so first of all we need to install it so I'm going to just copy this npm install cloudinary and let's go to the second terminal and I'm going to just paste it and now I'll go to view API Keys you can see that so you need to go here and we need these things right Cloud name API key AP now I'm noticing every time is that whatever videos I'll be creating you all will be using my creden sometimes I'll get this
kind of email or notification please don't do this just simply create account it will not take much time and after this once we'll do that we need to just import it from cloud in and the config will be very simple so it will be cloud. config you need to pass the cloud name API key and API secret now if you see all of this will be getting here right so now we have already installed so now let's go to our EnV file and then I'm going to just create all the EnV right because we need all of these environment variables so I'm going to do this one as let's do this one as cloud inary cloud name then we need cloudinary API key and then we need cloudinary API secret I'll go there and I'll copy all of this let's copy this
and also I'm going to copy the secret save it and now let's go to our root and then I'm going to create let's create a config so we going to create a cloudinary config file so I'm going to go here remember I told you that either you can create config or we can also create helpers but this will be a configurate so we going to name the folder name as config and here I'm going to create cloudinary do Js so now first we need to import it so I do const cloudinary and this will be we first need the package so I'm going to import cloud inary and if you see we need to import this version two so here I'll go there and Dot and you can see that we getting this V2 now here you just do simply Cloud inary this will eject a method which is config and you need to pass all these so first you need to pass a uh Cloud name next you need to pass a API key and then
you need to pass a API secret so here we are going to use process right because we already using process. EnV Dot and we need to use this Cloud name I'll copy this and I'll paste it two times so this will be cloudinary API key and this will be API Secret right and then don't forget to export this so we're going to do module.
exports and this will be cloud inary and this is as simple as that this very very simple now once you'll create this Cloud inary what I told you right that we need to basically first uh upload that to our cloudinary storage so we go here right you'll be getting this media library if I go here I already have some of the images that I uploaded for other projects so you'll get all of this uploaded file here so you can see that I have some images I don't know see some other people actually using this see you can see that I don't know from where these all are coming so that is the reason I'm telling that please don't use this right uh just create your own and then try to use all of these but anyway that's fine so now let's go there and then what we are going to do now I'm going to create another folder and now I'm going to give this one name as helpers because this will be our cloudinary helpers uh where we going to write the logic so here let's give this a name as cloudinary helper so look Cloud
dinary helper. JS so here first we need to import this cloud in config because this config we needed right all of these so here I'll go there and I'll do const cloud dinary and this will be require and here I'll go to our config and then I'll import the cloud now here first I'll create a method and this will be const upload to Cloud dinary so this will be a sync method and what this will receive right this will receive the file that we are going to upload okay so usually it will receive a file path so I'll take this file path as input and then I'll take a try catch block so try catch so this will be error and I'll do a console do error that error while
uploading to cloud inary and we're going to log the error and after this I'm going to throw a new error so let's do a throw new error and we'll just throw this let's copy this and we'll paste it here okay and then we're going to do a module dot exports and we'll do this one as upload to cloudinary so named export we can do the reason because we can have multiple helpers here in the tri block we need to now upload it so uploading will be very very simple if you go here let's see that how they're doing so you can see that they're doing this AIT cloud. uploader do upload this is the method and here they're passing the c or path whatever you want to pass and based on that you'll be getting the result as simple as that it's very very simple now I'll go there all right so here we'll simply do const result so use have it and we're going to call this cloud inary and then this will give you
uploader and then upload method right and here we need to pass this file path now what will be the result correct so let me just quickly sorry show you so if you go here right and see this is how the response will look so you can see that we having asset ID and also you're having a public ID now this is very very important this we are going to store it uh because let's in future you want to up update the resource or let's say you want to delete the asset or image you need this public ID right because whenever you'll upload a image to cloud inary and then you'll get the URL back and then you are uploading that URL to mongod so if you only delete it from mongod that is not the case right so you also need to delete from cloud in then you can delete that URL from mongod in both the places or else it's like your from your database the asset is not there but it's still present in your Cloud energy storage so you'll be getting this public ID and all the other things you can see that there is also a resource type which is image and then you'll be getting this URL and secure
URL both so these two things we actually need in our case right as simple as that because we are going to create now here uh this result we are going to return two things so let's do a return so I'm going to do a result sorry url url will be this result Dot and you can see that we having this secure URL and then we'll be getting a public ID right so this will be result dot public ID so these two things we needed as simple as that so now our helper is also done so now whenever we will be uploading an image we need to First Call call this helper correct this will upload to your cloud storage and it will give you this URL and public ID now if you go to the model it will be clear now this URL we are going to store in this schema or in your collection along with this public ID so now we need to create a controllers so we'll do step by step so now let's go there and then we're going to create a image controllers right now again you can give
this on a storage controllers or whatever you can also play with let's say I'm using image you can also try with video and that is how you learn it's not like whatever I'm teaching you that is the end of the world what I'm trying to say like so there are lot of things we are not touching in this video because this is only for beginners I'm repeating this point again and again I will definitely create a part two of this but if you if I am teaching image upload it's not like you only need to learn image upload you can try by yourself some other things let's say try videos try multiple images right at then end the concept will be same so here this will be image up uh image controller.js and here I'm going to create our first controller so first uh let's import our model here right so you need image and I'm going to do require and let's go to our models and then image right now I'm going to create our upload image controller so upload image so this will be a sync method so we'll get our request response
and first I'll take a try catch right so let's log the error and after this I'm going to race. status of 500 do Json so I'll do success as false and message al something went [Music] wrong please try again all right so here the first thing we need to check this request so whenever we'll be uploading uh let's say let's think of this scenario right that we have discussed that if you are uploading an image from your front end so you you're going to pass that image path correct or the file file for uh file data from your front end to back end so this request object will contain that file right but if the file is missing so in that case we need to return error so that we are going to to check that if so check if file is missing in request
object so do if not equal to request. file so here we are going to return race. status of 400. Json and here I'm going to do a success as false and then I'm going to do let's remove this and I'm going to do a messages that uh file is required please upload an image so this if the file is missing once this is if this is not missing then we are going to upload this to Cloud so upload to cloud inary and here I'm going to do const then you'll get something that we going to discuss so I'm going to call AET right and then remember we have created this cloudinary upload to cloudinary helper so this we're going to import in this
file so I'm going to do const get this from so we do require and I'll go to helpers and then we'll go to cloudinary Helper and here we need our upload to cloudinary correct so I'm going to call this so upload to cloudinary and remember sorry this will be upload to cloudinary and remember this will need a file path what will be the file path so it will be request do file and this will have a path and what this will return so this will return this URL and the public ID so I'm going to copy this so we get this URL and also I'm going to get the public ID so these two things we are going to get once we'll get this now what it's very simple right so now we going to store this in our mongod database so now once the upload is completed now store the image URL and public ID along with the uploaded user ID in
database so here we are going to do const New Image we'll do newly uploaded image so this will be New Image Right image is our model so this image and here we're going to pass all of this so we'll pass our URL because this is the first thing we need to pass we're going to pass our public ID and also pass the uploaded by now this part I'm going to discuss that what we are doing here so uploaded y will be request dot I'll tell you why okay now don't worry that from where it is coming because all of this will be interconnected and I'm going to explain each and everything that what we have done first I'll go to my middleware once middleware means my or middleware and you'll see that what we passing so you're passing a user info correct so here I'll do request do userinfo dot now let's go to our Au controller and what this user inpo has user ID I'll tell you what we are doing okay this part so now this will store
all of this and then we're going to call AIT and we'll do newly created image. save so I'm going to call this and this will store in our database and now I'm going to do raise. status of 2011 and I'm going to do do Json so in this case now success will be true and message will be image uploaded successfully and I'm going to use my image and I'm going to pass this newly created image sorry newly uploaded image and this part is now done okay so now first I'm going to export it so I'll do module dot exports and this will be upload image now till this part is done now what will be our next step so we created our uh cloudinary config we created cloudinary helper created image model
and also the controller so now we to create the routes correct so go to routes and let's create a image routes dot JS so here the first thing what we need to do so the first here we need our Express so we do const Express this will be require Express and then I'm going to create the router first because I always forget this part so we do express.
router and I'm going going to do module do exports and this will be router so this part is done now first of all we need to check something right so while we'll upload a image so here we'll be having two URL right two endpoint or route one will be to upload the image and one will be to get all the images now here we are going to do upload image how upload image will work now it's this from this point it will be very very important so you need to uh give more attention here so I'm going to do router and this will be a post method and let's give this one name as/ upload the first thing we need to do we need to pass multiple middle Wares here and it's very very very important what will be the first middleware now let's go to our uh let's go to admin routes right now if you see that we are passing this o
middleware and then then we're passing this admin middleware now I already told you right that each and every time a middleware function will be getting called Next function will be getting called once the middleware will execute and it will call the next function so one once o middleware will be getting called it will pass the data whatever this o middleware is returning so you'll be you'll be able to access that data in your admin middleware right let's say there is one more middleware after this so this middleware will be able to access data from both the middle wees correct something like that now here what we are going to do simply okay let me just undo this first I'm going to pass or we we are going to protect this upload image route so I'm going to first get our authentication middleware right so we need to get this so we'll go to our admin routes and I need this o middleware and admin middleware both so I'm going to copy this and let's paste it here so pass it so this will be o middleware and then
this o middleware will also pass the user information and this admin middleware will do if the user is admin user or not so I'll pass admin middleware okay so this is done now what we're going to do right will be using this multer middleware now let's say you have some kind of requirement that you need to store your images locally also now this multer will give you lot of properties so some of the properties we are going to see how how we are going to use this but first let me just quickly install it so let's copy it from here and then I'll just pass it and install it quickly so first because we are doing a single image upload so we need to create some uh middleware that will handle this image upload functionality so we'll go there so let's go to our middleware and I'm going to create image or let's do upload middleware do JS now first thing we need multer so I'm going to get malter which
will be require malter and also I need a path now these things we have already discussed I need the path module so I'll do require path all right now after this first we need to set our multer storage all right now how we are going to create the storage now let's go there in the documentation and let's see the disk storage right so have disk storage now if I go below so you can see that what is it is telling that this disk storage will give you full control on storing file to disk right so you need to pass a destination that in which folder you want to create or upload your images and also there is is a file name method right and then you're going to create the storage based on this now first go there and let's do const storage and this will be malter we are going to use disk storage
and here as I already told you we need to pass destination right in which folder we need to create it so here this will be function so here let's see what it is giving right so this will give you the request object a file that you're uploading and and a call function so right so here we are going to get the request get the file and this function and now I'm going to just call this and here you see one thing is very very important that it is telling that which path I want to upload that so here let's pass null and let's say I want to upload in my uploads folder so in my root file in this root project I'm going to create a upload folder so let's give uploads now it's very very important this should be there right we need to make sure that this directory is exist so there is upload folder now I'll tell that okay I want to upload all my images in these upload folders so I'll do uploads and give slash now let's quickly
check the spelling once so we have uploads this is fine now after this we're going to use a file name method which will be again function so do request file and then here we'll simply call this and we to we need to create so let me just quickly show you I'll search for file name so you can see that here this is used to determine that what the file should be named inside the folder right so here you can give some uh unique values like for example you can append some current date with the file name something like that also we going to do so first how we are going to create this right so let's give first we'll take our file so this file will give you a field name so you can see that we have a field name and then I want to append with this let's say hyphen and I want to add my date so do date do now and then I want to extract the path so path do extension name and then we're
going to pass the original name here so file. original name now this will create that file name unique file name and this file will be stored inside this upload folders I hope you're getting now this is done so storage you have now created now you're going to check We'll add some file filter function here so here we'll create const uh check file filter so this will be request file and here we're going to Simply check so let me just show [Music] you so here you can see that this will give you the this mime type of the file this we are going to use to check that whether it should accept image files if you're uploading videos so you can based on that you can add those properties so here I'm going to take if this file that we are having dot mime type dot starts with so it's only starts with
image and here we are going to call this and we'll pass this one as true that means this is successful else we need to throw some error so we'll do new error now this why I'm not explaining because these all are plain JavaScript Concepts right how you can throw error and everything so we can give like this is not an error not an image uh please upload only images right so this we are checking that if it's a image or not and now we need to create our middle we so I'm going to create my multer middleware because this middleware we are going to use in our in our routes because in our routes we already have protected the routes and also we checking if the user is admin user or not so here I'm going to create my multer middleware right so here I'll do module do exports so this will be multer and here we need to pass so let let me just quickly show you so we will be having some storage so you can see that we are having this
storage and also we can pass just one minute we need to check that is I'm checking the limits so there will be some property H this one so you can see that what options we can pass so it normally accepts a object right where you can pass the storage like wa to store your files so this we have already created our storage then it will accept file filter like which files are accepted this also you created this is our file filter and at the end there is a limits that what will be the maximum uploaded limit if it crosses so it will give you some error or something it will block you to upload so now I'm going to create it so first we need to pass the storage right so this will be the storage so here I'm going to pass storage which will be our storage the storage that we are having then we having the file filter which is our this
check file filter and then we're going to pass the limits and I'm going to pass limits file size I will do 5 MB so here I'll do five into 1024 into 1024 so this will be a 5 MB file size limit okay so now this will create our multer middleware so I hope you getting what are the steps that we have done here now we'll go back to our image routes so let's go there and here what we're going to pass we are going to pass this multer middleware also right so here we are going to first let's import it so we do const we do upload middleware this will be reare and here we need to go to middleware and we'll go to upload now after this we'll just come
here and then we'll pass it so we'll do upload image sorry upload middleware dot so here you can see that we'll be getting this and any array fills all of this because we're uploading single so I'll pass that this will be single and I want to only upload image okay this will be image and at the end once all of this is done now we are going to use our middleware which not middleware the controller which is this upload image controller right so now I'm going to go there and let's import it so const upload image now if you are confusing you also can give this on name as controller sorry I think we need to import it in that is a named export right so let me change the name it's a name tort so I'll just save it and I'll go there so first let me just go to that path so go to controllers image
controller and this will be upload image controller and then we're going to pass this upload image controller here all right and this is done now let's save it now let's go through all the steps one by one that how we it is happening right so first thing remember I told you that this part we'll discuss what how this is coming this request.
user info now if you notice this image controller is actually at the end and before that we have running multiple middlewares so this o middleware will return the user info remember we are storing the user info in token and this user info will be able to access in our controller correct so now if you go to image controller so that is the reason you are getting this request user info.
user ID and the reason is because we are passing this Au Delware then we are checking if the user is admin user then we are uploading a single file and at the end we are storing that image in our database now let's go to our server.js and I'm going to copy this now let's create Sol const do upload image routes this will be reer so go to routes and this will be image routes now I'll go there let's copy or let's do app.
use so here we'll do SL API slash image and then we're going to pass this upload image routes and I think till this part this is done I think that shouldn't be any error let's see if there are any error or not all right there is no error now now it's time to start testing it so now let's go there I'm going to go to log login user I'll create a new token now token is created so now I'll go there and let's go to let's check this if it is working or not okay now I'm going to create one new request and I'll do upload an image so this will be a post let's copy this so this will be/ API SL uh I think it will be image right so let me quickly check image and then we need to use the upload
so image/ upload we need to go to okay first we need to get our [Music] token and then go there first I'll just send it let's see what is happening so we don't have any token so first you need to provide the token so go to bror and pass this token and send it now let's see what is see now you're getting file is required please upload in image and this is coming from your controller so there is no file I'll go there and then we'll go to body and then you need to go to this form data right and here you need to pass the key so let's give this on as image this will be a file and then we're going to select some files so now let's select this one and let's say I want to upload that this image and let's open this and now let's send it and let's see if we are getting any error or not let's wait for some time awesome fantastic it is done so now
we are getting true imag is uploaded successfully and you getting the E public ID uploaded by ID this is the ID created and and updated it if you go there let's go to mongod devv and now I'll go to images so there is URL ID and public ID it's working right awesome and if you notice this uploaded by is nothing but the user ID right this is the user ID of that particular user and if I go to receive a74 let's go to users so you can see that a74 this is suum 2 and this is a admin user correct now if I try to go there let's I'll go to login I'll give only this send it so this is the normal user I'll go copy this go to uploaded image authorization and I'm going to now just simply replace this with this and send
it what fine right it's working fine awesome so you're getting admin rights are required so you can't access it until unless see what I admin so now this is the whole process so now let's go through all of this one by one so first what we have done first uh we created our model that what are the things we needed then we created our cloudinary config then we created the helper which will upload it in our Cloud inary then we created our controllers so in the controllers will be creating this URL and public ID once we'll upload and then we're storing then we go to routes we protect the route using Au middleware admin middleware and we use this multer to upload the image now if I go there and let's go to upload see there is image and if I click here this will be that image which we uploaded awesome right now I'll show you one very interesting thing very very important and that is let's say you don't want to once you'll save this you want to remove this file from your local machine so how you're going to do that so for this one
simply go to your controller and import file system so this will be reare fs and once you upload it right save and then I'm going to do let's say delete the file from local storage so I'll do FS do un uh unlink sync and then I'm going to do request. file. paath so now let's save it now let's go there go to login let's login with admin user send it copy this go there replace this go to body and then I'm going to to just remove this and select different let's use this one open and I'm going to send
it so you're getting uploaded successful if you go there right let's go here see there is only one image you notice there is that previous image but that new image is not uploaded here that is because we are removing it after uploading so you can use this unlink uh sync to remove that from the local but if you remove this right if I remove this line let's save it and let's try to use a different image let's say this one open and then I'm going to send it so this is done and if you go there right let's go to see there is another image is uploaded now fine right awesome so now this is all about the complete flow how you can do upload and also how you can protect protect so that only admin user can upload right if you remove this line from here then anyone can upload so that is the reason we're protecting using this middleware so now in the next part we are going to implement how we can fet all the images that we have uploaded so let's do that
in the next part all right so now let's start creating our controller for getting all the images right or fing all the images so here we'll Lo Fage images controller so let's do sync and let's do a try and catch and let's log it here now one thing while you'll be fetching right so it will be pretty simple but you need to keep one thing in mind is that only users who have authenticated they only will be able to access these images or else not but while uploading the images that time we have given two layer of security like first you need to authenticate as well as you need to you need to be a admin user both so here we'll do const and I'll do images so we do AIT and I'll do image do find right and now this will give you all the images and I'm going to Simply images then I'll simply do here raise.
status of 200. Json and let's do a success as true and data I'm going to pass the emage images that's it so for now this will be this much simple now let's copy this and let's pass it here now let's go to our image routes so now we need to import it so fetch images controller and now here we are going to Simply do router dog and I'll do get and I'm going to pass this fetch all controller now will this work no right because if you do like this then anyone can access the image so what we need to do we need to protect this route and for this one we're going to pass our Au middle and this part we have multiple time discussed that how it will work now let's go there and then I'm going to create one more request and let's do fetch images list or let's do fetch uploaded images now we'll go here and
let's copy this and we'll pass it the first thing you see if I go to get and then send this request so you can see that we getting access denied correct and that this makes sense so now let's do one thing let's go to register and user and I'm going to create one more user here John one and we'll keep roll user and I'll send it so now user is registered successfully and I'll go to login in user and then we'll get the token so now I'm going to copy this and let's just go to authorization select b error and then I'm going to just pass it and send it here and now you can see that we are getting all the images right and this is fine so now with this I'm pretty sure you'll be able to create basic level of authentication and authorization how you can protect routes and everything now one thing I want to mention is that see this is not the everything that we have covered in this particular section there are lot of things believe me if this video will be
like more than 10 hours of length and if I need to create a video on authorization and authentication I can create complete video of 10 hours on this particular topic only now you can understand that how many topics we haven't covered and the reason is because we can't cover everything in one single video right I'm going to create a separate video that will take some time but I'm pretty sure I I will definitely going to upload that also but if you're a beginner this part is more than enough so what will be your homework from this particular section right see again I'm repeating you need to create all of these projects once again without watching the video try to implement a register logic try to do a login page get the token and try to protect some routes and now again you no need to do the same way that I have done you can apply your own logic and try to do by your own so with this the part one of this project is done so what will be the next step here so next we are going to implement couple of uh functionality the first thing we need to do here and that is uh so if you see the admin user can upload an image right so
we are going to also Implement a delete image functionality now when we'll be deleting an particular image only the user who have uploaded the image they can only delete it or else not right the second thing we are going to implement will be implementing a forget pass sorry change password functionality so user will be able to change their password all right and then we also will be implementing some uh sorting and pag and logic uh while fetching the images so these three things we to implement in the next section so first we'll start with the first logic which will be or first functionality which will be change password so let's start working on that particular section all right everyone so now let's go to our o middleware and now I'm going to create sorry not mware uh we need to go to Au controller so now let's create one more controller here and this will be change password now we need to also understand that how this password change password
functionality will work now again whenever you'll be doing any function you need to visualize that from a UI perspective like how these things will work in the front end and then how you'll be getting the data and based on that you are going to implement the functionality I hope you're getting right see how change password will work see whenever you are going to change the password you need to be authenticated user that means without authentication you can't access your user page right so you need to login and then only you'll be able to change the password so first we need to take a try and we'll do a catch and now let's log here and I'll make this one e now the first thing what we need to do first we need to get our user ID this is very important and that user ID we will be getting from our authentication medular because I as I already told you that you have to be logged in to to change the password so let's get our user ID first and this you will be getting from where if you remember let's go to our okay I
think it will be here only see we are passing this user ID in our access token and if you go to our Au middleware you'll see that you are uh passing this user info so user info. user ID will give you the current user ID right so here you need to do request. userinfo do user ID so this will give you the current user ID so how we are going to do it the first thing we need to uh get our old password and the new password so first you need to enter your old password see normally the website will work like that right so you need to enter your old password and then you'll be giving your new password and based on that you are going to change it now here we going to do that extract old and new password right and here here we are going to do const and we'll do old password now again one very interesting thing when you'll be passing these two things from the front end right so you need to you will be typing something in
your front end and and uh you'll be giving the new password and the old password what you need to manage from front end is that let's say your your old password and the new password both are same so in that case you need to manage that validation from your front end obviously you can do that in the back end also but you that is not that much big deal so you can handle it so let's say you you are creating a react project and you are typing your old password as 1 2 3 4 5 6 and you are giving a new password also SI as 1 2 3 4 5 6 and you click on submit so in that case you can you can uh check that validation from the front end that okay your old and new password can't be same and you will not allow user to submit the form correct I hope you're getting so here we'll be getting our old password and I'll be getting my new password and this I want to get from request. body so this is the second step now we need to find our user right because we have user multiple user let's say there are thousand users so how we are going to get the current user that which user is actually changing the password so we'll
be getting from this user ID so we to find the current loged in user and I'm going to do here const user this will be AIT so user and we need to do what find by ID right and here you need to was this user ID that's it and after this we are going to check if this user doesn't exist in our database collection so we going to return arise.
status of 400. Json and I'm going to do a success as false and I'll do messages user not found all right and after this we're going to check that if the old password is correct very very important right old password is correct so when you'll be giving one let's say your password is stored as 1 2 3 4 5 6 but from the front end you're passing as 1 2 3 4 6 5 this is your old password so both should match right then only you'll be able to do it or you will understand okay this user is a valid user so this part also you need to check so how we are going to check it so simply do const e password match and I'm going to Simply do AIT bcrypt now this will give you the compare method right and here I'm going to pass the old password which I'll be
getting from our request. body and the new uh user password from where we'll be getting see from this user so if I do here user dot you'll see that you'll be getting the password right if this this password is not [Music] matching so means this user is not a uh sorry not this user so this that means your old password whatever you entered in your front end that is wrong so return return a 400 here because that will be error so 400.
Json and I'm going to do a success as false and message I'm going to do that old password is not correct please try again okay once all of this is done now we don't have any other age cases so now whatever new password we are going to store we need to has it correct we are not going to directly store this so we'll do has the password now so we do has the new password here right so Lon I'm going to create again the salt I think this part you have already discuss and we'll do bcrypt do J Sal and I'll pass the S Str and I'm going to do const new H password and this will be AIT bcrypt do
has so we'll pass the new password and then I'm going to pass the salt right and then I'm going to update the user password now we'll do update user password so this will be user which is your current user that you are having here this user do password will be your new H password this one and after this I'm going to Simply do AIT user Dove and this is is done so we have done lot of steps and at the end you need to definitely going to return 200 do Json I always written in this format success true now again this format also you can change it it's not a big deal it's based on your project requirement and everything so now I'll do password changed successfully right so now let's see what
we have done first we get the current user ID then we get the old password and the new password from request. body then we getting the find current user which is from the user ID here now we're checking if the user is not present so this user is not found in our database then we going to check if the old password is correct or not if not that means your old password is incorrect so you need to try again and once all the age cases are handled then we're going to Sol the new password and then we going to has it and then store the new has password so this is done so now let's do a change password password let's save it and now let's go to our Au routes so we'll get the change password and this will be simply router. poost I'll do change password and I'm going to pass this change password here and with this this is done so now let's do all the steps one by one first I'll go to register an user and I'm
going to do John 10 and I'll do John 10 and I'm going to keep this one as 1 2 3 4 56 okay and I'm going to register this user so registered successfully we'll go to login and I'm going to do John 10 and let's do this one as 56 so send it so now you're getting this this is fine so I'm going to copy this token go to fet uploaded images and I'll just send one second and you'll be getting the result this is fine now I'll create one more request and I'll do change password logic so this will be a post and we'll go here so what is the route name right so that we need to check once we'll go to server so/ API SL so we do SL API SL SL as change password right and now what we need to
pass here now one very very interesting thing that I mistake sorry my bad that is in our o routes we need to uh protect this with authentication middleware right sorry about that because I already mentioned it until unless you are logged and you will not be able to change the password so that we need to get it so let's go to our middleware and I want Au middleware and this will be my sorry what is the name of this let me just check so we have okay I think this is default export okay let's get the O middleware so we do o middleware and I'm going to pass it here because we need to protect it so now this is done so now let's go there and uh I need to go to my login user correct I already created the token so I'll copy this and I'll go and then just pass it here and I'll go to body Go to Raw and
then I'm going to pass here old password which is 1 2 3 4 5 6 and I'm going to do new password which is 1 2 3 4 5 6 7 8 right and now let's send it so password is now changed successfully awesome let's go to login and user and try to login now let's see what is happening see invalid password awesome now I'm going to do 78 send it we're getting and now let's copy this and let's go to our fet uploaded images and now let's send it so you you'll be able to log but I want to also check the upload and image right if I go here right let's go to authorization and let's change this see what will happen here send it see you're getting access denied ad me right required so that means change password logic is working fine now whatever I've done just go through and try to implement by your own
right all of this so this is done now what will be the next step so next step we are going to implement that that image delete functionality and also in that one you are going to understand that how we will delete that image not on from mongod but also we need to delete from the cloudinary correct because that cloudinary is working as a storage or like a middle man so when you'll be directly deleting something from mongod you also need to delete it from your Cloud energy storage that is very important so let's start working on that part from the next section so let's go to our uh image controller and we need to create one more so I'm going to do here const delete image controller and let's do here and then I'll do catch and just copy paste because I don't want to write the same thing again and again so let's copy this one paste it here and I'm going to pass error here all right so now we need to understand how we are going to delete
the image now I'm going to just give give you the summary of all the process that we are going to do see first you need to understand that which you want to delete correct that is the first step so you need to get the image ID what is the Second Step Second Step you need to get the user ID means which user is deleting that image let's say there are two admins the first admin uploaded an image and the second admin is trying to delete that particular image so it should not happen right so that's why we need both image ID and the user ID correct once we'll get the image ID we are going to find the current image and then we'll check that if that particular image is uploaded by that user or not if not we are going to return like that you are not authorized to delete this image because you haven't uploaded it correct now what we going to do once that is done you no need to simply delete it immediately from mongod TV what you need to do you need to delete first from your cloudinary storage once that is done then only you are going to delete it from your mongodb so this will be the whole process so now
let's do step by step so first I'll do const I'll do get get current image [Music] ID get current ID of image to be deleted now again why I'm keeping long name so that it will be easy to understand whatever you like you just give it okay I see some people also will give these kind of comments in my videos like why you're writing odd names but they will not understand that these things I do so that you all can understand very easily there is no point right you can give whatever you like it's have I told anything like that you need to exactly copy what I'm writing each and every video I create if you notice that I always always mention that don't write everything I do just try to get the idea and then try applying your own knowledge and that is the way you will basically learn now here I will get the user ID and this I will get from our middleware and now by this point I'm pretty sure we don't have to explain
only this we have done multiple times so these two things we we are getting next we are going to find the current image all right so we do image so we'll do EV it and then we're having the image which is our model and I'll do find by ID right so find by ID I'm going to pass this gate current ID of this image which has to be deleted if this image is not there so that means we also need to return see it's very slow I don't know why and I'm going to Simply return return a status of 44. Json and I'll do success as false and I'll do a message of image not found okay and after this we need to check here now so what we need to check check if this image is uploaded by the current user who is trying to delete
this image right so how we are going to check it now remember if I go to the image let's go to image there is uploaded by and here we have give the reference of the user let's go here right if you go to the F uploaded images there is uploaded by which is the ID of that user correct so now we can simply do it if this image do uploaded by dot to string so here I'm going to Simply do if this is not equal to equal to the current user ID that means what that means some other user is trying to delete this image which should not happen so you're going to do a 43 and I'll do a Jon we do success as false and message will be you are not authorized to
delete this image if you try to keep this more simpler and you can also I can also add something like this because so you you should not add this in in your real project but I just you can keep it like this but I'm adding for your uh for the explanation purpose because you haven't haven't uploaded it I need to give template literals okay so now this is done now we are returning here and after this what we need to do so now you need to delete this image first from your cloudinary storage so simply do so first we need to import the cloud in so we'll do const so let me just check what from which file we have I think in the not this one I think we we have this config and Cloud inary so we'll do cloud
inary and I'll do require and I'll go to config cloud in so now let's go below and I'm going to Simply do AIT and here we are going to call this cloudinary dot uploader dot destroy that means you are deleting destroy means you are deleting and here what you need to first remember we have this see how these all are linked so in the image you have this public ID I told you first time right this ID is required to delete anything right so here what we going to do image.
public ID will give you the ID and this will delete it once this is delete now you can delete the image so now delete this image from mongodb database so do AIT image do find by ID and delete and you're going to pass the image ID so this is get current ID of image to be deleted and this is done so now we'll do race Dot status of 200 do Json and I'll do success as true and I'll do message as image deleted successfully okay so this is all the things we need to do and now I'll go here and let's do delete image controller save it so now what will be the next step now you need to understand
that what you need to use here the first of all if you go to the uh admin routes not admin routes I think image routes and here now you need to do delete right so first you need to get the delete image controller and we do delete image route and this will be router. delete correct and here what we're going to pass we'll pass the ID because this ID we need right this ID will be if I go here this ID is nothing but this image ID that we need to pass but how we'll be getting the user ID user ID will be able to get because we need to protect it right so this o middleware will give you the user ID so I'm going to pass the au middleware but not only Au middleware also we need to check what we need to also check the admin middleware because if the user is not admin they will not be able to delete it again you need to pass the admin middleware and after this you need to was the
delete image controller right so now let's save all of this now this should work so now let's go there so first what I'll do right I'll go to login user sorry registered user let's do step by step and I'm going to do some different let's give bar and I'll give here this and I'm going to make this user as admin and I'm going to register this user successfully let's go here and we'll go to bury and what is the we 1 2 3 4 5 6 all right so now let's send it so I got the token now let's copy this go to upload an image and I'll just send it here let's go to body we go to form data and I'm going to remove this and let's upload some different image so I'm going to select this all right and now let's send this let's see so we get this right and now we need to check this ID the ID means this is that
ID this is the ID of that image but this is the ID of that very user right so I'm going to copy this with 71 this is what we'll be getting so we'll keep it keep a note here so now what I'll do simply you'll go here and I'll just uh copy this and let's say I'm going to not copy this I'll create a request let's do a delete a image right and we are going to send it and let's do a delete and then image and here what we need to pass we need to pass the image ID image ID how we will be getting so we'll get from here right this is the image ID so this I'll copy from here this is just now we have deleted sorry not deleted uploaded so here I'm going to pass pass it now in the authorization token what I'll do right now notice one thing here instead of passing the token off from the bar user what I'll do right I will pass from some different user and step by step we need to check so here
let's do this one as John 10 and I'll just send it so you get the token now remember this is not admin user correct this is a normal user so I'll copy this go to delete an image go to authorization and I'm going to do be a token and I'll just simply pass it here and let's try to send here so we don't have admin access so that that means the first check is completed sorry these two checks now we need to check this image remember very very very important this image is uploaded by Berry right but what I'll do right now I'll go to register and I'll use something else tell me some some other name I'll give Raj so I'll do Raj and I'll do make this one user also as admin so user register successfully go to login and I'll make this one Raj send it okay so this will be 1 2 3 4 5 6 so get the token now remember that image was uploaded by Berry but I am trying to delete it from this Raj token
which is also admin user and that should not happen so I'll go to delete an image and I'll just replace this with this and now let's send it let's see see awesome right so you are not authorized to delete it because you haven't uploaded it now let's go to login I'm going to make this one to Berry and I'll just send it and now I'm going to copy this go to delete an image and I'll just replace with this token and now let's send it see image is now deleted successfully awesome now if I go here you'll not be able to see it but you need to understand the whole process how this is working right you see almost all the things are completely protected and it's working perfectly fine right so that means if you have uploaded the image then only you'll be able to delete it not other admin users also will not be able to delete that so with this this part is done now let's move on to the next section all right so now we are going to implement some basic level of sorting and pagination but before that let's
quickly understand some of the concept that how we are going to implement pagination right so pagination means let's say you're having very large amount of data let's say more than 10,000 right so 10,000 uh 10,000 data so instead of loading the data one time on page load what we are going to do we are going to render some kind of pagent So based on each and every page we are going to render some certain amount of data and we will give the user the preference that whatever page they will select based on that we are going to render it now the alternative of PAG will be nothing but the infinite scrolling so uh just like the Facebook Facebook feed right so every time you refresh it you'll get the current image and then you'll scroll up the next set of feed or blog post uh loads but here we are going to talk about the images so let's say we're having for now I'll do like 1 2 3 4 5 6 7 8 9 10 and here what we going to do right we need to have two things the first thing is that how many data we need to skip and how much data
we need to render so this is how you need to First think that way for example let's say currently we are having 10 images what I want to do every time I only want to render two images so two two two two two so five times right so what you'll do right so we'll have 1 2 3 4 and five so this is how the pages will look in your front end now how I get five so again I told you right so you have total number of images is 10 right and then what we need to Simply do that how much the limit or how many images or products or whatever you want to S at one time so in this case we only want to show two images so this will be total number of images divided by two so that means you'll be having five pages correct now let's say you want to render five images at once so in that case it will become 10 divided by five so you'll only have two two pages correct and each and every time you click let's say click on the first page so first page means I
need to let's say render these two correct so in that case we don't need to skip anything because we are at the first page but when I'll go to the second page what you need to do can you guess so you need to skip these two and you need to render this here again when you'll go to the third page that time you need to skip all the four and you need to render this and sixth one again when when you'll go to the fourth page you need to skip all of these you need to render these two and at the last of the page you need to skip all of these only you need to render the last so that means two things you need to understand right how what will be the limit limit means how many images you want to render and then what will be the skip or uh skip is again I already told you right that whatever images or how many images you are showing based on that you need to uh calculate that Skip and that we are going to see now I will go there let's go to our image controller and let's go to F image controller now here currently we don't have anything but we need to do quite a few uh logic
here the first thing I'll take a page variable and I'll explain what these things are doing the first thing I'll do part int so this will be request do [Music] query. page orse this will be first means from your front end side right so let's say click on the first page so in that case you'll be getting as one when you you'll click on the second page you'll be getting as two that means which is your current page as simple as that if you select on Fifth you'll get as five now after this we need to render the or check the limit so here your limit will be so again I'm going to do purse int so here I'm going to get limit from my query once again and this limit is nothing but as I already told you that how many images you want to show at a time so let's say it can be two it can be three it can be five it can be all 10 at once and or else by default I'll keep this one as five so by default I want to render five images and now you need to create the skip so means skip will be
like this so which is your current page let's say current page is your two you are in the second page so it will be page minus one so it will be 2 - one which is 1 into this limit now see I'll explain so let's see we're in the second page and your limit is 2 means when you'll go to the second page means you need to render this one and this one so how many you need to skip you need to skip two if you see the calculation right so you are in the second page so it will be 2 Min - 1 which is 1 and your limit is 2 so 1 into 2 will be 2 when you'll be in the third page so in that case it will become 3 - 1 2 and your limit is two so four so that means when you'll go to the third page so see how this works so you are skipping four and then you are showing this and this right when you're in the last page or whatever you need to calculate like this so this will be your Skip and this will be my limit correct so this is done after this I'll do con and I'll take a sort by this will be my request do query dot sort by or else I'll keep this one as
created at created at is nothing but this created at property so I want to Let's sort by the date is being created this image is being created so I'll keep this one as created at by default and then I'm going to do sort order so here again I'll do if the request do query do sort order if this is equal to as sync so I'm going to do one or else it will be minus one for descending and this is done so now let's calculate the total Total Image uh total images so this will be AIT and this will be image dot we have remember we have used this count documents which will give you the all the data and now I'm going to get the total pages that how many pages I need to create can you guess so what we need to do we do math. cell and here we are going to pass total images let's say you're having 10 images right and your limit is two so you are rendering only two images so it will be
five pages so here you need to render five pages if your total images is 10 right and you're rendering all the 10 images at a one once so your page will be one if it is 10 if it is let's say five so your page will be two something like that so these will be your total Pages all right and after this I'm going to do const I'll create a sort object and I'll do sort object sorry this will be sort object of that sort by which is this one which is the key name and this will be equal to the sort order so either we can do use descending or ascending now once all of this is done now we need to get our images so what will be the images so here it will be find and now I'm going to do a sort here so this is will be provided by mongus and you need to pass the sort object so I'm going to pass the sort object and then we need to skip it that how many we want to skip so skip will be nothing but you skip this here and then you need to
give the limit that how many you want to render so skip is how how much you want to skip and limit is how much you want to or how many you want to so so this will be our limit and that's it and now after this we will simply render so we are returning the data and let's say I want to return current page which will be my page I'll return total Pages which will be my total pages and then I'm going to render total images which will be my total images so which is this one this these total images sorry this will be total pages okay and data will be our images and this is done so now let's save it and let's see what is happening so go here and I'm going to log in with let's go to login and I'll do suum 2 and I'll just send it okay I think this might be
78 let's see okay now I get it now let's copy this go to fetch uploaded images and I'll simply replace it and I'll see what will happen if I now send this we are getting success one current page is currently one total pages is three and total images is 12 and now you can see that currently what is happening so let's start uh step by step first we have a current page is one so it will go here page is one so what will be the limit so limit again it's a five by default correct so how many you are having so you see total images you are having 12 so 12 divided by 5 so it will be three right because we are doing math math of cell math. cell so it will give you round round figure something like that so total pages will be three and now here you can see that how many images you getting one and then you're getting two uh then you're getting three then
you're getting four and then you're getting five so this is the basic scenario if you don't pass anything now I'll go here and see what will happen if I make this one as two means I only want to see two images at a time on for at one time and now I'll send it see what is happening see now it's changing so total images is 12 total pages is six because you are rendering only two images and you can see that you are getting only two images here now I want to check something I'll go to params and let's add our page here so I'm going to copy this and let's page I'll do page I'll pass and the value I'll give here as two okay so you can see that we getting page as two and now what will happen now noticed one thing this ID will change this two ID because currently we are in the current page one so if I now send this so now it is at second page and this is getting changed and you will see we are getting uh different data here so this will now give us page and now let's say I want to also sort it right and if you
notice one interesting thing is that it will be by default sorted by this now you want to check with a different property let's say you want to give something like uploaded by so you can just give that value and based on that you can uh experiment here but I just main thing we need to check that how you are going to taste this part so now what I'll do I'll go here and now notice one thing I'll make the page as three and I'll add one more which will be my limit so now this time I'll make the limit as so I'll do limit as let's say how many I want to do okay let's uh make this one as four and now let's send it now let's see what is happening you can see the current page will be in the three total pages will be three now why total pages is three because toal images are 12 and limit is 4 so 12 divided 4 is 3 and you can see that how many you are getting 1 2 3 and 4 right and this is working perfectly fine so this is how you need to uh work with sorting and also the pagination now page sorting part is
actually little bit simpler but pag is actually quite tricky so that is the reason this is why I created this visual diagram so that it will be easy to understand all right so now with this we have completed this particular project now let's move on to the next section so in this section we'll be learning some of the intermediate to advanc level of mongod Concepts and also in the next SE we are going to learn or basically create a very simple realtime chat application using socket so these two things we are going to learn in the next two sections the first thing what I've done right so I already created a blank project and let me just quickly show you what are the concepts main we will be focusing in this particular section so here you can see that we'll be learning what is aggregation pipeline in mongodb is how you can use common aggregation operators how what is the concept of document references and also how you can populate referen documents so these four things we are going to learn in this particular section and also if you see that I already created
one database because we already created database multiple times in the previous project so that is the reason I'm not I don't want to waste time creating another one okay now if you want you can definitely create by your own and I'm pretty sure by this point you'll be able to create a mongod database from scratch now here let's go there and then first I'm going to run npm in it hyphen y now once this is done we are going to install Express we use uh also install mongus these two things right and also in the meantime let's create our server.js okay let me just close this now once this is done we are going to install node one also because we'll be using node one to run our server okay let's open another terminal here it's taking some time so in the meantime we can install node one also all right so let's do npm install
node mod and we'll do save Dave okay so let's go there and let's quickly change the this one to server.js and also we going to create one start script so this will be server.js and here I'm going to create a d script which will be node modon server.js all right okay I think let me just I think it's doing the same template so I think need not saved so let me just close this and I'll open again and then I'll just paste it here save it so this is done now let's go to our server.js so here we need to create our main server right so we need Express I do const Express will be reer Express and let's create our app so I'll do con app which will be Express and here uh let's do one thing
let's create our EnV file and also I'm going to create EnV so do npm install. EnV so in the do EnV file I need the U and also I need a port so Port I'm going to keep 3,000 and I just copy from here and let's paste it here all right now first we'll go to our server.
js and on the top I'm going to import EnV do config right so this is done so after this here I'm going to connect to our uh database so we'll do mongos all right so I think we also need to import mongos so we do reord mongus so this will be mongus do connect so this will be process. env. U dot then so here let's log this we do console.
log that mongodb connected successfully if there are any error so you're going to log it so do console. log error so this is done now after this we also need to use our Express Json middleware right so we do use midle words so we'll do app.use and do express.js and for now we are just going to create our server so app.
listen and I'm going to pass process. env. port and here we're going to just log that server is now running server is now running on Port 3,000 right so we copy this and just pass it here now let's save it and now let's see what is happening so I'm going to do npm run Dev so let's see whether the mongod is getting connected or not all right so it's connected success way all right so first thing what we need to do right see if I want I can definitely explain some of the concepts and uh it will be over but what I will do right I'll be creating a very very simple code example and using those code examples only I'll I'll try to explain all these Concepts mainly these four right so first let's go and then let's start creating the proper folder
structure so I'm going to go to uh here and then let's create a models and I'm going to create a product do JS so this will be our product model now here the very very important thing is that whatever schema that you'll be creating right the uh the properties that you'll be having you need to uh basically attention that properly because all the things will be interconnected and that is the main concept what we are going to learn that how you can refer one uh ref uh one uh uh collection to another collection how you can use these operators especially the common aggregation operator this is very important like if you're creating very advanced level of projects these two things will be very very helpful right populating referenced all documents this is also a very important concept the first thing let's get our mongus so we do reer mongos and I'm going to create a product schema so I'll do product schema so this will be new mongus do schema so here I'll pass a name and I'll
keep this on as string and my product will also have a category this also will be a string then it will have a price which will be a number then I'll check that whether the this product is in stock or not so I'll do in stock this will be a Boolean and then this products will have some tags which will be Arrow of string so do string here so this all will be our schema or properties that this single product will have now I'm going to do mongos sorry module do exports and this will be mongus do model and here I'm going to pass product and I'll do product schema all right so this is done let's save it so now we'll go here and then we'll start create our first controller so let's create our controllers and I'll create
product controller.js okay so first thing because we don't have any form or anything right so we need to First push some of the sample data so that is the reason you can see that I already created some sample data so each and every object will have a name category price inst stock and some tags okay so first let's go here and we need to get our product schema here so con product and this will be require so we'll go to models and let's go to product now here first I'm going to create a method so let's give this one as insert let's do sample products because we if you want you can create a form and then you can create one endpoint and create your products but this is not the point because this croud application or CR Concepts we already have covered in the previous section so there is no point of repeating same thing again and again and the video length will be long rate so that is the reason I'm creating some sample products so here it will be asking we'll have request response and
I'm going to do a try catch so in the catch just simply log this error and I'm going to do AAS do status of 500. Json success will will be false and message will be some error occurred okay now here we need to uh get our sample products first go there and let me quickly just copy this and I'll paste it here now simply we'll just do const result and we'll do AIT now here you are going to learn one more important property and now you need to call your product and if you see till this part what we have done while creating we have used this create method of mongus right or we use this save method but here you
you are uh pushing multiple products into your mongod database so to multiple things we need to use this insert many right so this is one of the method which will insert multiple collection or properties see insert one or more documents into a single insert many sell uh call to your mongodb server so here simply you need to BU the sample products I don't know why it's little slow but now I'm going to do raise.
status of 2011. Json success will be true and here I'm going to pass my uh data so let's do this one as so we will do we need to check that whether all the products are inserted or not so we will do inserted and I'll do result because this result will have the length right so we will do dot length so that we'll be able to understand that if all are inserted or not so these many sample products we have post right so now let's save it and this is done now we need to export it so we do module do exports and this will be what is the names insert sample products save it so now we created controller now we'll go here and create our routes and I'll do product routes.js now here let's create our first route
which will be this insert route so do Express so we need Express and now I'm going to create router so this will be Express dot router and now let's first do module. exports and I'm going to export this router now here we'll do router. poost and I'll just do a sample I'll do uh we'll do like add and I'll pass this sample products right so we do const so we need to get it from our controllers and then let's go to our product controller so we have this insert sample products so now I'm going to pass it here now till this part we have done multiple times right so this will be pretty simple now we need to go
to our server.js and we need to get our product routes so Lon product routes which will be reer and then we'll go to routes and then product routes and here what you need to do so you need to use this so do app.use and I'll do here/ products which will be our base ordl and then I'm going to pass the product outs now let's save it so till this part is done so that means if I go to/ products slash add I'll calling this and then this will push all this data in our database so now let's go to our Postman I'll create a new collection blank collection now here let's give this one as okay this is little slow let's give this one as or mongod intermediate so here I'm going to create our first
request and this will be add products so this will be post and let's go there and then let's copy the URL so this will be SL API sorry not/ SL products slash add and then I'll simply send it so we have we inserted five sample products right so all the five sample products are now inserted now we will start with our first concept so what is our first concept first concept is how we can use this aggregation pipeline so let's say there is some uh we are going to learn how we can for example some of the very intermediate level of properties like how you can filter documents right also how you can group documents multiple things and then on top of it you can sort your results and all of these we
are going to combine and create one query right and this query because we are doing multiple queries this is why it's called as aggregate right so we need to check it how we are going to do it first thing is that I am going to create one more controller here and this will be const and I'll give this one name as let's say gate product stats so this will be as sync I'll do request response so do a try cat so in the catch I'm going to just log the same thing so we go here copy this and we'll paste it here all right now let's say you have this requirement the first thing you need to filter so if I go to my sample products right so let's do it step by step or else it will be little tricky to understand if you see that you have the sample products and here you are having this inst stock as true in some places and then some places say inst stock is false right and then you have a price so now uh let's
say you have a requirement like first you need to filter the documents or products where the inst stock will be true and your price is greater than 100 so that is your first uh filter condition that you need to do so first I'm going to do a const result and here we'll do AIT and I'm going to call the product and here you need to use this dot aggregate right now here this inside this we need to take a array and here we are going to take our first condition right so first condition will be we need to check that which products in stock is true and price is greater than 100 so that means we need to use this match operator here so we do match right so this will match and here you need to pass all the properties that which is matching that particular query that you want to render for example here you need to do in stock so if you see if I don't uh sorry not don't write means if I
write here so this will be in stock and you need to pass the value that which will condition satisfies here right so you need in stock as true so you need to pass true here if you do false so it will only give you which as instock as false right so you'll go there and we do in stock as true and I'm going to do Price Right Price is another property and here I'm going to use use the greater than operator here and this will be 100 that means you're telling that where the price is greater than 100 that's it now for now let's not do anything and I'll just simply do raise. status of 200 and I'll do J Json we'll do success as two and I'm going to pass the data which will be my result this result okay now let's go here and let's export it so do get product stats save it and now we'll go to product routes we'll get
here I'm going to copy this so this will router. get and this will be stats so this will be get product stats now here let's go one more time and see what is the condition that we given we given the inst stock as two and price should be greater than 100 now first let's go ahead let's see how many are satisfying so see this is one one product this is satisfying this is second product which is satisfying this is not so we have two and you see we have true but price is less than 89 so only two products still now and this is also less than 100 so we should get two products as a result now let's go to our Postman and then try to create one more request loate product stats so copy this so this will be stats and I'm going to send it all right so we not getting anything this is interesting so we need to check if we are doing something wrong or
not okay let's see here let's go to our model ones oh sorry this will be in stock a capital sorry my bad so that is the reason so we need to do instruct true now let's send it okay something again got I don't know what happened okay let me just save it one more time and then let's go here and try to send it okay so this is fine so how many data we are getting only two right so if you see here we having instock is true price is greater than 100 in Stu true price is greater than 100 this is fine now I'll go here let's go to our product controller and then I'm going to make this one as false and let's check what is the so we are having only one false and the price is $1 199 okay so that means if I now save this and send
it we should get one result here okay so getting one result but if I just go here and let's say let's do one thing let's do this one as greater than 500 and now let's save this and now let's go there send it one more time we are getting no result and this is correct because we don't have any product with this uh but if I now make this on true save and let's send it we should be getting I think there are some problem with my Wi-Fi request uh sorry Network request so now we are getting True Result so we having price is $999 and price is $6.99 which is greater than 500 awesome but now let's make this one as 100 this is not the thing we need to add more condition here so here what we have done so in this stage we filter the documents right so we check that if the document in stock is true and the price
is greater than 100 so here we are getting the follow result now we need to go to our stage two so here this is our stage one let's give not here after this so this is our stage one now here after this we are going to add our second uh condition which will be we need to group our documents so how we are going to group it so let's say we have this criteria that you need to group with uh the category all the products you need to group by category and then you are going to calculate the average price for each and every category right and also you need to count the number of products in each category so what I mean by that so you have a category Electronics then again you have a category Electronics same Electronics here you have a sports and then category books so what we are trying to do we will be grouping all the products based on this category which is let's say this is electronics category right and after this we're going to calculate the average price average
price of each category okay so average price means let's say this is price $9.99 then it is $6.99 And1 199 which has all has Electronics category so you're going to calculate the average price and also you're going to count the number of products in each category so that means if this Electronics has three products Sports has only let's say one and books has one so these we are going to calculate okay and this uh should give us all the summary of our product catalog okay so now let's say how we are going to do that so this will be our stage two which will be to group our group documents so let's use here so you need to use group property right so you're are going to group it so here you need to pass the ID so I'll pass my ID and you need to tell that by what property you are going to filter it or group it not sorry filter group it so we are going to filter using category right so we'll give this and then you need to pass the key name so if you go here you
have a key name category this this is the key name so this you need to pass here so I'm going to I am grouping by category and then I want to get our average price so I'll do average and then I'm going to calculate price so this will be my average price and then here you're going to pass average and you need to again when you're doing average you need to tell by which property you want to calculate the average so in this case I want to get average of the price right so here you need to pass here so that okay give me the average of all the price that belongs to this category correct so this is done and at the end we need to get the count now here you are going to pass sum and then you'll pass here one now this will give you the grouping now let's save it and now let's see what is happening here now let's go there and I'm going to just send it one more
time so see what you getting very very important now here you need to check it how this is working first we'll go there okay first you need to remember that when we have done this in stock is true and price is greater than 100 and if you go here right in this case you are having one so this is in stock is true price is greater than 100 then in stock true price is greater than 100 which is two and then again you have I think these two only right so we have Electronics one Electronics 2 and then you can see that Electronics we have a three but here in stock is false so that means there is only two products very very important so this is why you are getting count as two ID you are getting electronics and this is the average price average price is giving the average price of this plus this divided by two okay so this is what you're getting so let's say if I go to calculator and let's do 999 plus
699 divided by 2 you'll be getting 849 this is what exactly you are getting here right so means what we doing we are aggregating multiple condition and creating one query right so first we have fil we have filtered and then we grouped okay all right so now we know that how we can can aggregate multiple condition and then create one single query now we are going to understand how we can use some of the common aggregate uh operators here so this part so I'm going to create one more method here and for this one let's give as get product analysis and this will be also as sync request response and here I'm going to take try catch and let's log this here and now I'll paste it all right so the first thing I think we have already
understand how we can use the match operator but let's do one thing first criteria will be here we need to match filter documents uh based on specific criteria that we have already done just like for category we need to only get all the products with the category as Electronics so here I'm going to just do that one as first steps I'll do result we do AIT product do Aggregate and here we will be taking our match operator so I'll do match and how we are going to do it now here we need to pass the key right so you're telling that okay I want the category to be Electronics now here let's copy this and I'll pass it here so that means isans give me all the products where the category is electronics so this is the first now I'm going to do r. status of 200 do Json so we do success as true and data I'm going to pass this
result now let's copy this and I'm going to pass it here let's go to product routes paste it and then we'll do rout router doget and I'll do here analysis and I'll pass it here let's save it now this part I'm pretty sure you'll be able to understand because this we have already learned that how we can use the match operator still I just want to do it one more time and I'll do this one as let's do get product analysis so now let's copy this and I'll do here analysis now let's send it so we are getting three products now right because it's only matching the category so having one two and three awesome now I want to do something else I want to use some common uh operator
here aggregate operator or I want to group it so I want to group something like this the first thing I want to Group doc douments so that it will calculate the total revenue or it will give me the sum of all the prices that how many products you are having that is the first thing then we are going to learn how you can use the average operator so average operator calculates the average price then we have the max operator Max operator finds the highest price and the mean operator right so this is how we are going to do it so first we are matching all of this with category electronics and on top of it we are going to group it right so here I'll take one more and I'm going to do use group so the first thing here I want to pass the ID as null and here I'm going to do a total revenue and I'll use my sum operator here now again when you're doing the sum and everything you need to specify that which property you are targeting so again I'm targeting my price property this is important or else it will not be
able to understand right next uh I want to do here app average price so average price again I'll use the average operator now in the average operator also you need to tell that I want to use the price next I want to get my Max product price so let's do Max product price so here we use the max operator right so this Max operator will give us the maximum price of that product so I'll do price once again and then let's copy this and I'll do here mean product price and this will be mean and this is done now let's save it and now let's go there and let's see what is happening now send see so here now you're getting idal that is fine so total revenue will be getting this average price is this this is the max product price and this is the main product price and if you see there if you add all of the electronics
product you'll get this total as Revenue and also it you you will get the average price as this so this is how you need to use it right now I want to tell you one more operator and that is called the project operator so project operator what it does right so it it will reses all the documents by specifying that which field you want to include so if you want to include any field you need to pass as one if you want to exclude it you need to pass as zero so let's see how we are going to do it so again if you see how we are doing sequentially so first we have doing match then we have done grouping and now I'm doing using the project operator so here I'll use project now again because you see we pass the ID as null so here I'll tell that okay for this ID property I don't want to get this so I will pass as zero right so that means this will not get and then I'll pass the I'll get the total revenue I'll pass one I want to get the average price also I'll pass as one I'll get the max product price I'll get one I'll get
mean product price I'll get one and let's one more I'll do a price range here and in this price range what I'll do right I'll use the substract property here so I want to substract and then I want to pass here my Max price sorry Max product price so let me call copy this and I want to use the mean product price so this is done now let's see what we are getting the result right now remember this format here and I'm going to send it one more time okay we are getting some error I think something is problem here okay I don't see any problem let's see what we doing wrong here so ID Zer total Revenue then we are having average price Max product
price mean product price then we having sorry this will be substract that is the reason okay so now let's see it so now let's go there and let's send it see what you're getting so now you're not getting the ID property remove you see that that excluded because you have passed as zero go here and pass as one save it and now send it one more time okay I think it's taking some time to load now you see we are getting the ID here right so if you go here and I'll make this one a Zer one again and now I'll send it so now you're getting not getting this so total revenue you're getting average price Max product price main product price and your C substract it's giving 800 right so this is how you need to use the common aggregate operators right I'm pretty sure now this will give
you some very basic idea I not say this will cover everything we can't cover each and every Concept in a single video right so that is the reason I've designed such a way that so that at least it will give you some basic idea and from there you can research by your own and then try to create project by applying this concept so now we need to understand uh two more things which will be the document references and how we can populate referenced documents so let's do that in the next section all right everyone so now we need to understand the document references right so for that I'm going to create one more model here and I'm going to give this your name as author. JS now this section also will be very important because you are going to mostly use this in your projects also and this will be reer and this will be mongus and here I'm going to do const and this will be author schema and this will be new mongos do schema so this will have a name so this is the name of the author so let's will be a string and then we'll have a bio
which also will be a string now here I'm going to just do module do exports so you have a model sorry mongos do model and I'm going to name the collection as author now this is important actually okay and then I'm going to pass my author schema save it now what I'll do right I'll create one more model here and this will be my book model so means let's say each and every author can write multiple books right okay so then what we need to do we need to reference this author in this books collection and we need to see how we are going to do that so first thing again we need to get this so let me just quickly copy this and we'll paste it here and I'll do const and this will be book schema so this will be new mongus do schema and here let's say book will have a
title which will be a string and this will also have a year and this will be a number right right and or let's remove this I think only title is also fine and then this will have a author now here the main point is come of the concept now what we're going to do right we we are going to reference here that this book is referred to this particular collection that means let's say I'm an author so I can write a particular book right so I need to map it so here I'm going to do author and here we need to give a type so this type will be so this type will be here mongus dot schema do types dot object ID right and now we need to pass a r property here this ra property will refer to that particular collection that just now we have created so here it will be author so now I'm referring this to my author doc uh collection okay so this is how you need to do this and at the
end I'm going to do module. exports and this will be mongus do model and I'll give this one as book and this will be my book schema all right so this is done so now we need to go to our controllers and I'll create a book controller.js all right so now let's create our first controller so so first I'm going to import both models that just now we have created so we do require so we'll go to models author and then I'm going to get my book which will be require I'll go to models and then book so let's create our first controller which will be create author so this will be as sync request
response so we'll do try catch and here I'm going to just log this so L console.log error and here I'm going to do erase. status of 500 do Jason do success as false and message will be some error record now let's copy this and then I'm going to create one more which will be to create book so I have two controllers now I'm going to just do module do exports so I'm going to export the create author and also create book but here this is not the point because this part we have already done that how we can create new books products or create new documents and save it in our database here the point is how we are going to learn this concept that how we can populate
reference document now we already have referenced this author in our book collection correct using this ref now here let's go to our routes and let's create book routes.js so let me just copy it from here in of rewriting every time so I'm going to copy this and here this will be our book controller and this will be create author and then we'll be having create book now let's save it and at the end we're going to create so we'll do router.
poost so this will be uh let's give this one as author or let's do uh let's keep this one as author and then we're going to keep this one as create author uh author then I'll do here router. poost this will be book and this will be create book now let's export it so do module. exports and this will be our router so now let's save it let's go to our server.
js and I'm going to import it so this will be my book routes and I'm going to use it here so let's uh give this one as books books or we can give this one as reference because we are learning reference here right so we'll give this one as book routes let's save it now first thing uh we need to go here and then I'm going to create one more request we'll do add new author so this we are going to create first so we do post and then we'll go here and this will be reference because we're learning the reference concept and/ author now let's go here and if you see in the author we have a name and we have a bio so we'll go to body let's go to raw and I'm going to pass here name and I'll pass my name
here and bio I'll give like SS bio so this is done now let's send it oh sorry my mistake guys really really my mistake we haven't learn done any logic here my bad so here what we need to do simply first we need to create author so this will be AIT so we'll do simply author this one and then we're going to pass our request.
body and then I'm going to do AIT author do save remember we are using the save method to save a particular document oh sorry we need to do this one as new author so this will be do save and then I'm going to Simply do race status of 2011. Json so success will be true and here I'm going to pass my data which will be my author so this this author that we have created so now let's go here now I'm going to send this response so we getting suum bio and this is the ID right so now the point is how we are going to create a new book now now to create a new book also it will be pretty simple so what you can do right simply copy this and then we'll pass it here and I'm
going to make this one as book so this will be new book so book is nothing but the model and this will be book do save and then I'm going to pass the book here now while creating what you need to do right if you go to the book model you see that this has a title and there is author in the author we are going to pass the ID of this author so this is the new author that we have created that means the book that we are creating that book is WR uh written by this author okay so I'm go here and let's do add request and I'll do add new book and let's copy this paste it here so this will be auor SL book post body draw and then I'm going to pass here title so I'll do book and then uh let's do first book and here you need to pass what you need to pass the author now here you're
giving the reference now I'll go to my add new author and I'm going to copy this ID and now I'll pass it here okay and now let's send it so now we have a first author sorry first book which is a title this author means this author is created this or uh write this particular book and this is the ID of this book now now what I need to do right I need to populate something so I need to populate the book along with the author now in that case this reference will comes into picture this refer logic that we have written so I'll go to my book controller and I'll create one more method here and let's give this a name as get book so get book with author so this will be async request response so I'll do a try catch and now I'll copy this and paste it here and
now here what I'll do right now this is the point where you need to pay attention so I'm going to do a const book now see what I'm doing I'll do AIT and I'll do book dot find by ID and here I'm going to pass my ID so this will be request params do ID okay and here I need to do do populate now this is the place you need to understand so now I want to populate my author along with this book details so what this populate method will do this will replace the author reference with the actual author document right now what will happen this book. author will be having the full author object not just the ID now remember while creating the book we have only passed the ID of that particular auth author and that you are getting but because you are already referenced that particular author with this book collection so what will happen we we'll do populate and then you want
to populate the author so it will automatically give you the actual authored object and you are going to see it so now I'll simply do if not book is found so I'm going to return return a response. status of 44 and I do do Json so success will be false and message will be book not found or else I'm simply just return raise. status of 200.
Json and I'll do success as true and I'm going to pass the data as this book okay or let's uh let's keep it book so this is how we are doing so we are finding that book and then populating this author now let's copy this and then we're going to pass it here now let's go to book routes I'm going to copy this and here we are going to do one more route so I'll do a router.
get because now we are getting it and here we are going to do slash book slash ID and here we we are going to pass this get book with author so now this will give you both so now let's see how this will work so go there and I'll do new request I'll do get book with author uh data so now let's go here let's copy this so this will be get now after this book you need to pass the ID so where we'll be getting the ID I'll be getting the ID from from this so you need to pass the book ID right so you need to copy this here and then I'll pass it here as simple as that so what we doing we're doing SL book SL ID this ID is nothing but the book ID and I'm going to send it see what is happening now here the trick will come see you are getting the book information so this is the book ID
this is the title but in the author you're getting the actual author object right you're not getting the author ID back so if you see this ID is actually the author ID this is my name and this is the author bio so what is the advantage of doing the refer right so when you are referring this particular author collection in this book collection and you are populating this here so it will replace this with the actual author object and you will be getting that in the response so this is another very very important concept that you need to know and most of the time you'll be using so now we have covered all the four things right so with this section try to create a simple project and try to apply all the things that you have learned so far so that's all for this particular section now let's move on to the next one all right so now in this section we are going to learn how you can use node with socket right so first uh you need to understand what actually socket is so see socket is a library that enables Real Time by directional communication
right between your web clients and servers now let's say the web clients can be anything let's say you are using react view angular whatever so what it usually does it primarily uses web socket protocol but can fall back to other methods also like long polling if the web socket is not available now this section whatever we going to learn this will not be very extensive because uh this is a beginner level project right and if I spend more time on this so it will the length will be more and that is my only concern the video length right and if you see in this particular video we are covering lot of things right so that is the reason what I'm going to do I'll be creating a very simple chat application and while creating the chat application I'll try to explain all the popular and most used methods or how you can integrate your uh socket in your nodejs application the first thing what we need to do you can see that we need to install uh socket.io package right but before that let I'll just quickly create one uh blank folder and after that we are going to start creating the project all right so let's uh start uh
creating our package.json right so we'll do npm init minus y and uh before that we also I want to discuss one more thing that why we actually need socket.io or socket JS right see there are some advantages you need to understand and these kind of queries you also will get in your interview also see the first or most important functionality or usefulness of socket is that it will give you to access the realtime updates right so you it enables instant data transfer between client clients and your server so that is the first thing then as I already mentioned uh that it also enables B directional communication so what actually does that both your server side and the client side can initiate communication it also is event based right so it actually gives you to handling of different types of messages and accents and also the fallback support just now I discussed that it also automatically fall back to other channels if the web soet is not unavailable webset is not available right and also there are some built-in methods that we can use here so these
are the main advantages of using these sockets right and where we usually use this normally in chat application right realtime collaboration tools also gaming like lot of times in gaming application we use sockets and then most of the times also if you're creating any live admin dashboards or something so they are also used uh sockets the first thing what I'm going to do first we need to create or sorry not create we need to install our uh packages right so I'm going to install uh first we'll do with Express and also what is the name let me just check so we have a socket do IOU so let me quickly install it now all right so here I'm going to create our server.js okay so do server.js and go to package. JS and so I'll change this one to server.js and this I'll give start as node server.js so that is the first step
second thing what I'm going to do let's quickly create one sorry let's go here let's quick uh create a public folder here and here I'm going to create the first index.html so this will be our simple HTML structure that I want to create because until unless we visibly see this application this will be difficult to understand right so this time we need to create some now here this is not like you can only create HTML you can create whatever you can integrate with react view next W angular jQuery normal JavaScript not not normal JavaScript like any other web Frameworks or or simple HTML you can use but for now we are going to use HTML now here let's give this one as chat app and now let's inside body the first thing uh we will create our main user list container where we'll be rendering the list of users so here I'll take a div and let's give this one ID and let's give ID as user list all right and here I'm going to take a A3 and let's give this one as online users because once the user will
be entered we need to render the list of users in the chat after this I will take e and here I'm going to render all the users so I'll do take a ID of users so this is our first step the second thing what we need so I'm just simply creating the basic structure so after this this I need to create our chat container where we'll be typing and showing the chats okay so once user will type and hit enter we need to render or show the chats just like in Facebook or Instagram we usually use right so we'll do da and here I'm going to take a ID and I'll do this one as chat so this will be our chat container right and at the end we need to create our basic form so where we'll be typing the message now if you notice this structure is definitely will look very bad but that is fine that is not the thing we first need to understand how this works so here I'll take a form and let's give a ID here also so I'm going to take ID of message form and I'm going to take a input so let's give a type so I'm going
to take a type as text I'll give a ideas let's give this one as message input placeholder I'm going to give enter your message and I'm going to also give this one as Reit okay and there will be a button so I'm going to take a simple button and here I'm going to do send now because we're using form so I'm going to give a type as submit see that that is the reason at the beginning of this particular video I told you right that you need to have some idea of HTML CSS those things or uh it will be very difficult now what I'll do right I'll just let's do one thing let's uh okay first I'll do let's go to our server because first we need to understand some of the very basic or most useful methods or how we can create our connections and everything right so first in the server we need our Express so I'll take const and we'll do Express and we'll do require and this will be Express let me close it okay next we need HTTP right and HTTP module we have already covered
previously at the beginning and at the end we need our socket so I'm going to give this a name as socket IOU okay so here I'm need require and I'm going to do socket IO so this is the first step next we need to create our express application so I'm going to do const app and this will be Express and now the first thing we need to create a HTTP server now here uh you need to pause it and try to and uh try to do it by your yourself so that you'll be able to understand that whatever we have learned so whether you are able to apply those knowledges or not instead blindly writing whatever I'm doing here that is not the best way right so here I'm going to create our server and I'm going to do what so we need to do HTTP do create server right so this will create a server and what you need to pass you need to pass this app so now this will create our server next thing now we need to initiate our socket IO and then we need to attach that uh that particular uh initiation with our HTTP server right so
if I just comment it so we do initiate socket IO and then attach this to the HTTP server right because this is the server now how we can initiate right so we need to take so usually we'll take this one as IO and here you can see that we already have this socket IO and we'll take the socket IO here now here we need to tell that which server we are running so here we are sor not which server we have created so this is the server so now we need to attach This Server here all right so this is your initialization of your socket IO once this is done now what we need to do we need to we are actually created a public folder right and we need to serve the static files from the public directory from here so how we are going to do it so here we need to do so we do app. use and this Express will give you this static method and here you need to that which folder we are uh targeting here so this will be
our public folder so this is done now what we need to do we need to create our the first thing we need to create a connection now before that I want to explain some of the things or uh some of the very very importance Concept in socket the first thing is the connection so what is actually connection connection is established when your clients connects with the server right so you have a client side and server side when there is a connection happen that means socket iio connection is established right so in that case the connection event is fired and a socket object will be created and if you go to their official documentation right so you'll be getting all of this here and I highly highly recommend please go through it now here specifically you can go to the server section and the client section and just go to the initialization process and how you can create server instance and then what are the things and how it will work now first thing if you notice one thing as I already mentioned right that it works as a by directional communication way so what happens is that let's say you have
a server and a client right and you are emitting a event from your server you'll be able to listen it from your client similar way if you're emitting a event uh from a client side you'll be able to listen to it on the server side right now this is one thing so what it learns about the connection then we have the emit so this is how you can emit a event and this on method is to listen and then handle events both on the server and the client side and now this depends that for example if you're emitting from here you listen here you emitting from this side you listen that side all right so this all are the very very basic and the important methods that we need to know now let's go back to our code until this part we have created this so what this line is doing again if I repeat so this will serve the static files from the public directory because uh that is where we are having the index. HTML file now here let's say what I'm going to do right because we'll be having the user so whenever user will enter the chat application we need to store that user someplace right so for now we'll take a const users and I'll do a new set okay
and now we need to listen to the new socket connection so how we are going to do it so this IO will give you this on method and here you're going to pass connection now this will take the event right so here we will take connection and in this connection here we are going to take socket and first I'm going to just log it sorry I log it and I'll do like a user is now connected so that is the first step second thing what we are going to do we need to handle a couple of things the first thing we need to handle let me just give the comment so we need to handle users when they will join the chat so this is the first thing right then we need to handle our incoming chat messages and we need to also handle user disconnection okay now let's go to our
index. HTML now here what we are going to do first the first thing is that we have created this now let's go here and then after form I'm going to take a script scpt and here we'll take a source and I need to get our socket. i.j which is the client Side Package now if you go here right let me go to the installation of this client and if you see that by default the socket IO servers server exposes a client bundle which will be in this path see by default it it will be by default but if you want you can also use a CDN service so for now you already installed that server so what I'm going to do I'll go to socket.io SL we need to use socket. io.js right this is what we having let me just copy it to double confirm so we copy this and we'll paste it here right now after this we are going to create our main script logic which will be on the client side so I'll take a
script the first thing we need to connect to our socket iio server so here I'm going to take a socket and I'll just invoke it and here we need to first get the Dom element so what are the things that we need the first thing we need this chat where will be rendering the chat messages we need the user list right we need the message form and also we need the message input so these four things we need so after this I'm going to take each and everything step by step so let's do here so first we do con chat and here you can simply do document. get element by ID and you need to pass the chat because that is the ID here we are having right chat now after this I'll be having the user list so do users list which will be again document. get element by ID and this is the name of this I think users right so we have users that's it now after this we need message form so do message form which will be document. gate element by ID and
here we need to to get the message form and at the end we'll be having the message input so we do message input which will be document. get element by ID so having message input okay so these four things we need now the first thing whenever I will be entering the chat application I need to prompt the user to enter their username so I'm going to do a const username and this I'll take a prompt and I'll do a enter your username and once they will type something and after this we are going to show that okay this user is now joined now once this is done here very very very important so let's go here now what we are going to do right let's go to the socket instance now we are going to emit our first event from the client side so what we are going to emit the the the event name will be joined so whenever
user will be joined I'm going to emit that event here and that event I'm going to listen in the server site okay and this is what I already told you now here I'm going to Simply do socket that we have created and this will emit our first which will be joined so this is the event name and here I'm going to pass the usern name that which user is now joining so this is the first step uh so first step now we need to go to our server.
js and here if you see let me just save it the event name joined so what we need to do so after this here we need to take socket do on correct and on means we need to add uh see if you see here it adds The Listener function whatever you can read it but what I'll explain in a simpler way is that when you'll emit event from here you are going to listen it as simple as that and here you need to give the same name what you have given here which will be join so simply you listening to this join event and and once this will join so what this will give you this will give you the username correct this is the username so here you'll take the username that you'll be receiving and here I'm going to Simply add that user in the user list so I'm going to do users do add and I'm going to pass this username here as simple as that right now very very very important see now for example if a user is uh adding for the first time that is fine but let's say now second time is second
user joined so what I need to do I need to inform the first user okay there is another user is joined means we need to broadcast that you broadcast that message to all the users and to broadcast a particular uh event what we need to do right we need to use io. emit right so here what we are going to do we need to let me just comment here so broadcast now broadcast to all clients or users whatever you can give users that a new user is joined new user has joined right and here I'm going to Simply do IO now see if you what I I'll do here now I'm emitting from here so now I'm emitting a event from on the server side so and I'll give the name as user joint see how this is working this is working in a by directional way right you're emitting from client side you're listening on the server side again you are emitting from the server side you'll be listening on the client side so you're emitting us user has joined and now what you'll give you'll pass the usern name correct because this is the user which has
joined once this is done now we need to send the updated list of users to the all clients now here I'm going to emit another event now this will be send the updated user list to all clients so I'm going to do i.it and I'm going to pass the user list so this will be my event name and here I'm going to pass what so I need to do a array right so do array.
form of that users and this users is this user set we are having so this is still this part this is done now let's save it now what we need to do again we need to go to our HTML right and let's go to our here till this part I hope this is clear now after this what we need to do simply let's go here on the server side so we have passed this user joint broadcast uh sorry not broadcast this event to the client side we are sending so we need to listen to it so after this we'll do socket right and socket.
on and I'm going to copy that event so user name sorry user join and what I'll get i'll get this user here so I'll take the user and here I'm going to do let's create a helper function here so I'm going to create a helper function like we do function and I'll do add message and I'll get the input here so I'll first I'll take const message element which will be we'll take document dot I'll create element and I'll take a div I'm going to do here message element do text content which will be equal to my input and here I'm going to append it in my chat container see if you see right we have a chat here so I'm going to Simply do chat do append child and I'm going to render this message element and now what
I'll do right I'll just scroll to the bottom of the chat container so I'll do chat do scrolltop will be chat do scroll height now this is fine now once this is done so now we'll go to our back to our user join event and here I'll simply pass this add message and I'm going to pass the users here so let give this one as so we do user and let's give this one as like uh has what we can give so L user uh has joined the chat okay so this is the first step so when the user will be joining now let's save it now first let's see what is happening so go here right so I'm going to run node server.js okay uh I think I don't know
why let's do npm Run start something we have done wrong is it oh my God man sorry guys see these kind of things I'll be doing most of the times we need to run uh our application in a port right that only we haven't done how it will work so now here I need to do cons Port which will be 3,000 I'll give and then I'll do server that we have created HTP server so I'll do listen I'll pass the port and then I'm going to do like server is now running right so we do log and we'll do server is now running so that is the reason I'm thinking what is happening so now let's do here node server.js so server is now running and I think it will be running on Local Host so let's give this on another thing so
I'll give Here Local Host 3,000 so we'll do running on we do HTTP Local Host and I'll give here the port save it so this is now running so let's copy this and I'm going to just paste it here so let's give my name here I'll give suum and let's do okay see it's joined the chat so you're getting right now I going to copy this and I'm going to just open incognit and paste it here now give Raj and let's do this on side by side I'll do okay see what is happening now obviously you are not getting this so you need to render all the available users here but Raj has now joined the chat so this part is working now definitely there are quite a few things we need to do that we haven't done now if you see here right also you're getting a user is Ed that is fine in the
server end sorry server side we are passing this user list also so we are emitting this event right so we have only handled the user join for now so on user joining we are showing it now we need to work on when user will left and also you need to handle when uh this user list also here so now let's go to index.
html one more time now after this right so this part we are going to create one more which will be so I'll do socket do on and you see the name of this I think user list so I'll copy this so I'll take user list and you see what you'll be getting you'll be getting the user list here so here I'm going to get our users user list let's go users list and here I'm going to Simply do so we have a user list right see this is the nor element so I'll simply do user list dot inner HTML right so okay sorry I think it's mismatching let's do this one as users so we do do inner HTML and I'm going to Simply do users do map and here we'll take our user and let's take a Ai and I'm going to Simply render the
user here so we do render the users so now let's save it now so I'm going to just close it let's refresh it one more time so I'll give my name so you can see that also I think we need to join it sorry my bad so we need to join here so we do join with space right so let's refresh this so getting both right you can see that now I'll just copy and open it one more time here so we do Raj or let's give another one John so you can see that John has joined the chat you're getting all of these now if this is getting a little confused so what we can do simply we also need to do one more time when user will be leaving it so you need to listen to another event which which will be user left okay so for now I'm going to just run it one more time from scratch and we'll see what is happening so now I'm going to
refresh it so I'll give this so s joined the chat let's copy this and I'll give Raj so now you're getting both two users copy it one more time and I'll give John and if I do side by side all of these right so you can see that we are getting null so this part also you need to handle but let me just refresh it one more time so I'll give John here enter I just want to show you that you can see that in all the places it's updating real time but if it is null that part we need to handle okay so that we are going to do but before that we need to finish the other events now second what we will do we need to handle one more right when user will be user will left the chat we need to remove that users right or we need to notify that okay this user has now left the chat okay now first thing what we are going to do let's go back to our server. JS and now till this part we have completed that user list now after
this we are going to handle our incoming chat messages but how we are going to handle the incoming chat messages right so to get the incoming message first you need to get the message from your client site so we need to emit that event from here and that you're are going to listen here right and this is what we have uh discussed till this part why I'm repeating these things again and again believe me if you're creating a simple application then only you'll be moving to intermediate to advanc level application or else it is very very difficult right so try to apply all of these and try to create by uh your own all the projects that I'm creating okay so let's start working on these two things so first we'll handle the handle incoming chat message and also at the end after this we're going to handle the user disconnection so this we're going to do in the next section okay so now first we need to handle this incoming chat message so as I already told you right so when user will be typing something in this form that we are having this form right so we need to handle it so let's go below and after this first I'm going to handle our form submission so first
we need to handle form submission so I'm going to take so we have this message form right message form so let's copy this so do message form. add event listener so I'm going to do here submit so we'll take sorry so we'll take a event and here we are going to first we'll do event do prevent default because this is the normal behavior so that the page will doesn't refresh every time you will enter the form after this we're going to get our value that user is typing on the input field so do const message text or let's do this one is extract message text and this will be message input dot value and then I'm going to trim it so I do trim and after this if this value is present so what we need to do as I already told in the previous section we need to emit a event right so we are going to emit the chat message event to the server with the message data so what is the message data message data is
nothing but this data which user is typing so I'm going to do again socket. Emit and I'm going to name this one as chat message right and here we are going to pass two things so the first thing we need to pass the username right so how we'll be getting the username I think us username will be getting from here so let's get the username first and then I'm going to pass a text which will be this extract message text now once this is done I'm going to clear this so I'm going to do message input do value will be empty okay so this is done so now we are emitting this chat message event so now we need to listen it on the server side so let's go back to our server now I'll do handle incoming chat message so what we'll do we'll do socket. one and the name is chat message correct so that is the event name and here what you'll get you'll get the message information which will have the username and the text so I'll get the message and here again we need to what
we need to do can you guess see when user will be typing the message we need to inform or show that message to all the users right because it's kind of a group chat so you need to broadcast that receive message to all the connected clients so we do broadcast the received uh okay received message to all the all connected clients so I'm going to do i.
it so again I'm going to do chat message and then I'm going to pass this message here all right so see we are getting that message again we are emitting here so what we need to do next so we need to again listen it correct so now we'll go back to our index.html and now after this user list I'm going to do so here what we are doing simply so I do listen so that you can understand so that is the reason giveing comment so now listen for chat message events from the server so I'm going to Simply do your socket.
on this will be chat message and here I'm going to get the message now this message is this message just now we emitted so this will be my message and here what I'll do simply I'll call the add message and we can simply render this thing right so we have message have a username this username and this message has a text so I'll render a message.
username then give colon and then I'm going to pass message Dot so I'll do here message. text so this is done so now let's save it until this part let's see if it is working or not so now I'm going to just close it one more time we'll start from scratch I'm going to close this let's refresh this so I'll give my name so I joined I'm going to copy this and here we'll just paste it so I'll do John and I'm going to do a Hello okay now let's send it see you're getting John hello now I'm going to I will do hi John so now I'll just send it here let's see what is happening send here see you're getting hi John fine right and I'll do some random message so do random send here
we're getting and I'll ask what is this enter you're getting in both the places right now if you notice this part that if you try to understand very carefully you'll be able to easily understand okay this is happening by directional way only so you emitting from the client side you're listening on the server side you're emitting from the server side you're listening on the client side right and even it will work with the multiple users very easily but what thing is now left so the main thing is is left is now you need to handle when the user or the this disconnection will happen right so you need to handle the user disconnection properly so that is the next thing so now let's go there and then I'm going to go to our server.js and I'm going to handle it so we'll do socket Doon right now here again once again we need to do disconnect sorry do disconnect now here we need to do couple of things
first I'll log here so I'll do a user is BL user uh is uh disconnected so after this I'm going to remove that users right so we do users. for sorry users. for so I'll get the user now how we you are going to get it right so we'll simply check if this user is equal toal to the socket do username that will be having so here I'm going to simply just do users.
delete that user and now I'm going to Simply broadcast so I'll do io. Emit and I'm going to pass a user left event and I'll pass this user here so this user has now left right and don't forget to send the updated user list so I'm going to do io. Emit and I'll pass the user list I think that is the what we having user list and this I'm going to again pass it here and I'll do array.
form and I'll pass the users and this will handle the disconnect but this is not yet done the reason is because we need to also handle it in our uh this HTML or client site so after this user join write this user joint I'm going to take socket. on and I will do user left because that is what we have given we are emitting here user left and this will give you the user right the current user so I'll do user and simply uh we are going to do add message and I'll pass here that this user has left the chat right all right so this is done now we need to do one more quick thing and that is if I go here right what I notice that uh we are using this disconnect and then we are using socket. username uh which we are getting from socket object but we
need to do one slight modification and that is once user will join we need to store that usern name in the socket object so do socket dot username equal to this username all right now let's save it and then rerun this and then we are going to see everything from scratch what is happening so let's refresh this so I'll give my name enter so now I joined and then I'll copy this and then open this and then here I'm going to give John and so John has now joined so now I'm going to just do a high so getting message I'll give hello we should be getting that and now what I'll do notice one thing so I'm going to close this John has now left and then this is updated and if you go here you can see that and user is disconnected this is getting called so this is uh a very simple chat application although this will work perfectly fine what you need to do if you want to make it complicated you need
to add some more functionality but at the end the concept is simple right so you're emitting some events and in the real time you're listening to on the client side or either on the server side and based on that you are writing the logic so with this till uh this section is now completed so the homework for this section will be try to create another chat application and try to apply some more features in that particular application and for that what you can do you can also go to their official dog and try to see how they are doing some of the things right now let's move on to the next section all right everyone so now we are in one of the most important and I'm pretty sure you all will be waiting for this particular section and that is how we can do deployment right and I'm going to show you multiple ways we can deploy nodejs uh back end right so first we'll start with render because I think render is one of the best way you can do this and uh the reason is because if you're using AWS or something then you need to add credit card information right so if you by chance if you don't have credit
card so then render will be a very good option to deploy your nodejs packet now remember before we uh we in our previous section we have completed all these sockets and everything right but before that we have created this nodejs o application remember this one so this project we will be deploying this one okay so what I will do right so I already open this here the first thing whenever you need to deploy any of your application first you need to push this to a GitHub reposit repository right so now it doesn't has to be only GitHub you can use other like bit bucket or something like that gitlab also you can use but I'm going to use G GitHub so what I'll do right uh I will create a new repository here and let's give this one name as we do YouTube nodejs O 2024 keep this one as public and this is important and then uh do create repository so now this will
create now let's go there now now before that we need to do one very important thing and that is you see that we have this node modules and the EnV file which holds some of the uh credentials and some secret variables that we don't want to expose to Publix right so we need we should not P this file so what we need to do we'll create a git ignore file so we'll do git ignore and here I'll add nodecore modules so means I'm telling that okay exclude these node modules and also we need to do EnV file so these two things I don't want to post whenever I will be posing this code to GitHub that is the first step so next thing what we need to do right next we need to initiate a GitHub git repository here so how we are going to do that so to initiate a git repository first of all you need to install git in your local machine and after that you need to run git in it so now you see that this will initiate a empty G repository and if you notice go here
you'll see that it is not adding the node modules and the EnV file here and this is what exactly we need now once we'll do this what we need to do we need to add all these files we need to commit it and then we are going to push it so now either you can do it from here so you can click this plus and then give commit message or you can do from here also so look G add okay so now see all of this will be be added and we'll give G commit minus M adding or we'll do pushing nodejs or changes all right but now you can't directly publish it so we need to link this repo with a new repo that we have created so we need to add this remote origin so I'm going to copy this and then we'll go here and and let's clear it and then I'm going to just hit
enter and now what we going to do simply just publish this bran so I'm going to click here and now changes are already post so if you go here right let's see what is happening so you can see that we have config controllers database helpers middleware model routes whatever other other things now before that we need to do one more thing and that is if you go here in the server.js you see that not server.
js sorry my bad we need to go to package.json and you see we have a start script okay and then we have a de script now we need to do some changes here because uh when we will be deploying this in our render so we need to tell render that okay I'm using node and I need to First install all the dependencies and even if you notied here right we have this de dependency which is actually not required uh this de dependency means this will be only required when we'll do the development right but this is not the thing so first we need to tell that okay first we will install all of this dependency and then we need to run this start command and this is very important so how we are going to do that so first let's go to our package.json and okay where is package.json and I'm going to remove this test script for now and I will do here node and then server .js now why server.js because this is a root file which will run if you given this one as
index or app.js you need to modify this one accordingly and then I'm going to do a build command here and build I will do here npm install now let's save it so now I'm going to push these changes so let's add this one one again so do clear and do get add and I'll clear again and I'll do get commit minus same and we'll do updating package Json file content all right and then simply we will post it all right so this is done so now let's refresh this so you're getting npm run build which will be which which will run or build and then the start so now this part is done and now I'll go to my render dashboard so first you need to log in here and then once you log in
you'll go to the dashboard click on new so you need to deploy web service once you'll go here you'll get all the git projects that you have created right if you have already connected your git so you can see that I have lot of uh projects here so I'm going to create my first project and do connect so here uh just keep the name as it is if you want you can change it node this will be node Branch will be master root directory so if your code inside any directory so you can specify here and then we have build command so you see here we have a build command here right so which is npm install so it is automatically taking this on or else you can also run npm run build right this also you can do or I think install is also fine now here this start command will be node server.js so you also have the start script here right so that also we can do so you can simply do here so let's do this one as npm run build and this will
be npm run start or you can also do npm start now here you need to select the what type you want to definitely we are going to use free and then we need to add uh environment variables right so this is is important now you see that we'll go here and let's go to our EnV files now I'll just simply copy all of this and here I am going to just add from EnV I'll do this one and I'll just paste it here now let's add this now all will be added now you see that this JWT secret key right this what we are having here this we need to create some unique key right so how we are going to do it now to create a unique JWT secret key we are going to use this open SSL now if you don't use this one so this will help you to create a secret key uh very strong secret key right so you need to just type it here go here on the first link and then you can simply download it
from here if you have 64 you have 32 you can download it from here and then you just need to run this op SSL Rand hyphen hex 64 if we just copy this and let's open the command and I'm going to run it so this will give you a strong secret key let's copy this and then I'm going to just paste it here all right so this is done now you can click on deploy web service now let me just quickly give you one of the recap that because if you're a complete beginner this will be quite tricky right so I'll just quickly give you whatever we have done so far so let's go to our code the first thing is that if you notice that whenever you'll be creating any project it's very very very important if you're using any variables or any secret thing always keep this all this in EnV right so that is the first step so that will be the first step and after this also we have added a git ignor right then we push our code to GitHub then we go to render we link our project with that GitHub project that we
have created and after this we have done all of this process so this is the name then okay one more thing that we added this uh script right so build will run npm install start will do node server.js node server.js is nothing but this is our starting file which is from our root uh directory which is this server.
js if you have app.js you need to change it accordingly if you have index.js you need to change this one accordingly now if you go here we have npm run build and then npm start so you can give npm start also select the free tire and add all the environment variables and create a strong secret key so now all of this is done now so I'm going to do deploy web service now let's wait for some time now once this is done we need to test it that what is happening here right so it's already running awesome so build is already successful so it's run this npm run build which will do npm install and now build is actually successful so let's wait for something it will deploy and then it will give you the URL and that URL we can we can test it and we'll see if it is working or not if you want you can also skip this
section I'm the reason why I'm not skipping or speeding up because if you for some people will comment that okay we are not able to understand like they will comment in in video so that is the reason I'm not skipping if you want you can skip it like one or two minutes and then you can go to the result that is also fine so now it will run npm start right which will run our server.
js file let's wait so mongod is also connected successfully awesome so you're getting all the logs and service is now live so now let's see what is happening so now we will be getting the URL which is this one so now I'm going to copy this let's go to our Postman and then I think we have this node just Au right and here we are using registered and user so I'm going to use this only let's see what is is happening okay so for now okay let's see one thing is okay I'll go there okay it's live now so now I need till this part so I'm going to replace this/ API SL register so I'll give some random name like Sam and we'll do Sam gmail.com I'll keep this one as user I'll send let's see what is happening user is registered successfully awesome so now we'll go to
login and user okay we need to just copy this right so I'll copy this login and user paste it and make this one as login and I'll do this one as Sam and try to send it invalid credentials correct remove it we'll be getting again and now I'll give the correct one and send we get the token awesome now we'll copy this okay first I'll copy this and then let's check our welcome route oh sorry sorry we have copied the whole thing I think let me copy only this part now let's go the here and then let's replace this/ API home/ welcome and we'll go there copy the token go to welcome route and I'm going to to paste it send it we are getting it's working
right so I'm pretty sure you'll be able to check the rest of the things but uh this is how you can do it right so you have seen all the step step by step now try to deploy it and then once you'll do two three times you'll be habituated all right now let's move on to the next one all right everyone so in the previous section uh we have learned that how you can deplay your node app in render now in this one I'm going to show you how you can do it in versal so I'm showing multiple options the reason is because everyone has their own choice and their own requirement So based on your convenience you will be able to deploy wherever you like all right so now see there are certain steps we need to follow while deploying in versel and first of all will be you need to create a folder uh you need to create a account as simple as that okay all right now let's go here and the first thing we need to do couple of things first whenever you will be deploying in versel we need to create a versel do Json file which will uh tell that the configuration of your project
okay and now if if you want to uh deploy this app using versal CLI so in that case you need to install versal globally and then you can run in your terminal versal command and you need to follow the steps okay so that is one way of doing but first let's uh start working on this uh first the configuration we need to create so let's go here and I'm going to do here verell do Json all right now here the first of all what we are going to do we need to do a couple of things first we need to give a version here so this version will be two now what this version does so this is nothing but uh this is telling that you are using this version two of that versal configuration format all right after this we need to use builds and here we need to take array and then inside this we need to take source and in Source you need to tell that which is your entry file right so
this in our case it will be server.js so you'll give server.js again what this does is that it will tell that this is the entry point of your application as simple as that after this we need to use a use and here you need to tell versel that I'm using no no so this will be at the versel SL node all right so this is one configuration that we need for builds and then we need to create for routes so I'll create one more which will be routes and inside this again we need to take Source now here uh very very important so we need to use a Rex which will tell that uh which will match all the incoming request and to write it we need to give slash and here we are going to give this sorry we need to give Dot and then this star and this is telling that okay this will match all the incoming request that you will be doing after deploying this application this will be for your route configuration and next thing what you need to do again you need to give a destination so what will be your destination it will be the
server.js again this will depend that what file name that you have given here so first uh let's go through so we have given a version in the builds you need to give the source so in the source it will take the server.js and here we are telling that okay I'm using the node and now here we are using routes we are telling uh we are giving a Rex in the source and the destination again will be your server.
js now we need to go to our package. Json okay now here you can see that while deploying in the render we have added this build command now if you want this is actually optional for this versal because versal will automatically run on the build command okay or basically they will install all the dependencies because this build command is doing nothing they're just installing all the dependencies so it will do automatically so you can simply remove it okay rest everything is fine because for the start we need actually node and server.js which will run our server.js file so this is all the changes that I want to do here and then I'll just add these changes so let's open our terminal and let's do clear okay it's already nothing is there want to clear well give G add and we add all then I'll do G commit minus M and I'll do modifying package Json file for versal deployment and let's P the
[Music] changes all right so this is done so now what we are going to do right let's go here and then I'm going to do add add new project and you can see that we already have connect continue with GitHub so let me just quickly log in I think it will be already login and I'll just import this now you'll see that we'll have some options right so we'll have a build and output options see it's already taking npm run build correct and output if you want to change all of this it will if there is a public if it is exist or else it will take this Dot if you want to change that again you need to overrate all of these right now the main thing is again environment variables we need to add so let's add all of this step by step so now we'll go here let's go to our EnV you can also upload EnV file directly and it will take all of this automatically so we go to EnV and then start with
Port so this will be 3,000 after this we'll have more URL let's copy this add after this we'll do JWT secret key which I'll create quickly so let's open command line and I'm going to copy and paste it here and I'll get it copy this and we'll paste it here at it then we have the cloud name then we'll copy the API key and at the end we'll be having the API secret
okay so these all the environment Vari we need now let's add this also so we have six and now just need to do deploy that's it let's click on deploy and let's wait for some time and once this is done we'll be uh getting the URL and we'll be able to test it let's expand this let's see what is happening all right it's very very simple so this already done so now let's go to dashboard now we'll be able to get the domain so let's say I'll get this one let's copy this and then I'll go to my Postman and I'm going to just run it once again here so let's paste it here so verell API
register and because we already have this user name so I'll give this one as Sam 10 and I'll do Sam 10 let's send it so user is registered successfully and it's actually live so that is the reason I want to show you now I'll go here login and let me just copy these let's go to login user I'll do Sam 10 and I'll give some random password send it invalid credential and I'll send it here you'll be getting the token and it is working fine now I don't want to teste all the other things you can check it let's say for example we'll get that first let me just copy this here from here and let's check the admin out okay so here I'm going to just paste it and then try to send it let's see what is happening so you don't have any token that is fine I'm going to copy this and
we'll go to here and I going to paste it and now send it and you can see that we have admin rights required so if I go to register and let's I'll do Sam 11 and I'll do this one as admin send it so registered successfully I'll go to Sam 11 send it we'll get the token copy this and now let's go to admin L and just replace it here send this you'll be getting the admin page and it's working absolutely fine so this is the whole process how you need to uh deploy your node app in versal so you have learned two things right in render and versal now let's move on to the next one all right every so welcome to a new section right so in this particular section we are going to learn how you can use dql with nodejs now as usual like my previous section so what we going to do right I will divide this particular section into two parts so in the first one we're going to learn the basics of graphql and after that we will
be uh creating one simple project where we are going to also learn how you can integrate your mongodb database with graph Quil right so first you need to understand what actually graph Quil is by the way graph kill is developed by Facebook and uh this is nothing just a query language for apis right now in the previous section we have already discussed right that how we can create our rest API development and everything now first you need to understand that what are the advantages of using graphql over race dlay the first and the most important one is that see graph c will allow you to do precise data fishing so what I mean by that let's say in normal uh R API how it will work right uh so for example we'll take this kind of scenario that you are having a form where you let's say creating a product and this product will have a title it will have a description the product will have a let's say price and some tags and then you'll submit the product you'll save that product in the database and then what you need to do on page load
you need to F the list of products what usually happen whenever you'll be fishing the data right so you need to get all of these title description price and tag in your API response although in your UI side or in your front end let's say you Crea a react T you are only rendering the title you are not using the description price and other uh properties from that product uh not okay now what graph Quil will give you so this graph Quil will allow clients to request exactly the data you need for example in this scenario let's say you only need the title so you can only get the title and it's actually huge huge Advantage right and now what will happen with this R API often leads to over fetching right that means we are getting more data than actually we needed and that is actually not good so this is one of the main advantages the second is graph uses single endpoint for all the data op ver on on the other side R API typically requires multiple end points for different kind of resources and
operation right and what will happen with this precise data fasing right it will definitely going to improve your performance right because by reducing the over fetching and the under fetching graph kale will significant improve application performance so these all are the basic difference or advantages of using of graph over HTP now there are some uh Concepts that we need to know in graphql so first uh we have mainly three types of operation the first one is called queries means how we going to fet data second one is mutations how we going to modify or write data and the third one is called subscription subscription is usually used for Real Time data uh real time data updates right right and we are not going to cover in this one in this particular section we will learn only the queries and the mutation section and if you're a complete beginner that will be the best starting point for you there is no point of learning subscription at the beginning on the once you go to intermediate level then you can uh start working on subscription and other U advanced level of Concepts also we are
going to learn that how we can create schemas how what kind of types and how you can create types everything from scratch the first what we are going to do I already created a blank folder you can see that now as I already told you that I'll be having two projects or two parts one will be the basic concepts and second one will be a project so what we'll do right let's do one thing I'm going to first create our as usual package.
json right so we'll do first we'll do npm in it iph Y and what are the things that we need here right see the first we need to install definitely graphql also we are going to use app server so we will use uh install app server and to write our schemas we are going to use this graph TR tank so let's install all of this let me just clear this and I'm going to do npm install so I'll do Appel server SL server then I'm going to install graphql and also I'm going to install graphql tag so for now these three things we're going to use this graph qu tag which will help helpful util it is for passing your queries and everything right so let's hit enter and then this will install and in the meantime I'm going to create a source folder inside of this and inside this Source folder I will be having our main server.js I'll do
server.js okay this will be our entry point now let's go to our package.json and we need to change couple of things the first thing is that this will change now so it will be Source SL server.js and then also I'm going to add a start script uh this will be node Source SL index.
js and also let's install nodemon also so I'm going to install node modon as a de dependency and here I'm going to add it here so we'll do a dep script so I'll do node mod Source SL index do JS okay I think let's copy this and let's reopen it one more time and I'll just paste it here also you need to change this one so let's copy and then okay why we are doing index.
js this will be server.js both all right so this is done now first thing as I already mentioned that we need to create the schemas and everything now before or discussing or writing the schemas first we need to understand that what actually schemas uh schemas are right see just like in our mongod or mongos we what we usually do right we create a different types of models now similarly in graphql the schema file will Define your schema for your project that you are creating now what actually that schema is that is nothing but the structure of your data or the operation that you will perform form for example let's say uh you are working I'm just giving example you are working with some product so this product can have let's say title right as I already told you then let's say this will have a price then it will have something else so this is nothing but the structure of your
data so you're telling that okay my product can have a title it will have a price similarly when you will be creating your first graph schema you need to tell graph that okay this is my product schema something like that okay because currently we will be using dummy data so before writing any schema let's go to sours and then here inside of this I'm going to create a data and Let's do let's create some dummy data so I'll create a products do JS and let's create some dummy data so I'll do const products so I'll give a ID so this will have ID of one let's say I'll give a title let's give this one as laptop then I'll have a category so I'll do this one as Electronics then let's give a price let's say 99095 and also I'm going to do a inst stock means whether the product is available or not which will be
true now let's copy this paste it two more times so this will be three uh let's make this on as s this I'll do Sports I'll do this on some random value and I'll make instock as false similarly let's do this one as two I'll do this one as uh what else we can do here let's give uh some tea or coffee so this will be food and here this I'll give some value and this instru will be true so now for now we will work with this data so I do module.
exports and this will be products all right now we will start creating our schema right so as I already told you so for now let's create a graph qu folder first so I'm going to do graphql and I'm going to create our first schema. JS so this file I'll just comment it this file will structure not structure this file will tell that what will be the structure of your data right as in a simple words so now let's start creating our first schema so for this one we will be using this graph qu tag that package you have installed right so I'm going to just import it so I'll do require and I'll use that graph ke tag and we are going to use this gql and let's create our type definition so I'm going to do const and we'll do
type depths so here you need to take this gql and now inside this you need to write all the types now you can compare this one with the schema that you usually create right so don't do it means I'm just tell telling you to so that it will be easy for you to understand so here you'll be now creating your first type so I'm going to do a type see so this type keyword you need to give and then the name so let's give this one as product so this is your type now inside this you need to specify that what kind of fields this product will have now for now we know that okay this is a dumy data so it will have ID it will have a title category price and instock but before that we also need to understand that what kind of data types or basic types this graph qu will provide so first it will Pro provide a string type and I'm pretty sure you already already familiar with this it will also give you int this will also give you
float it will also give you Boolean and now there is one more that I'm pretty sure if you are doing it for the first time you will not be aware and that is called a ID data type so this is nothing but a unique this is a unique identifier so it's just like uh I'll tell you what exactly is this identifier right see remember in the mongos you usually have this ID right which will tell the unique ID of that individual document so similarly in your graph qu you can give this ID so this ID is nothing but the unique identifier just like each and every product will have a ID okay so now let's write our uh so we need to structure it right so what are the things that we'll be having so first the product will have ID and sorry this will be a type of ID now here I'm going to use this uh symbol and what this symbol is telling that this is a non-null level field non-null level means this field is mandatory so that is the reason I'm using this next it this will have a title which also will be a
string and also this will be a non-nullable field then this will have a category so category also will be string and this will have a price price will be a float and then I'm going to use the inst stock because we'll be having this one and this will be a Boolean this is also mandatory so let's save it so now let's go through so we are creating giving a type we are telling that okay this will be the type and then inside this we are specifying that what are the fields or how our product type will look so these fields all the fields are mandatory once you'll create the type type now we are going to create our queries right so three things we need to know first one is the types second one is the queries that how we can create queries and the third one is the mutation now these queries also I'll make I'll try to make this on simpler so that you can understand so here you need to give this one as query and now you need to specify that what kind of
queries you'll be having now remember compare this one with while doing the R st a remember we have created the controller so how the controller was working so let's say you creating a Blog website and this blog will have multiple controllers right so let's say fet all the blogs then fet blog by ID right now these all are the quaries so here you what you're doing you're simply quiring this list of blogs here you're quiring the current blog by ID similarly here you also need to spec specify that what kind of quaries you will be having here so for now I you will be having two qu the first one will be to get the list of products and second one will be to get a single product by ID right so if I give one this would give me Product one if I give two this would give me Product two if I give three this would give me Product three so here I'm going to pass products now this is my quiry name okay and here you need to give the type so type will be product right let me just
comment it so this will be product but this will be array of products because you you can have multiple products so here you need to specify this as product and both will be non nullable so we are specifying this product type here and the second quy will'll be having the to get the single product so I'm going to do a product and here very very important because if you notice just like in our controller we usually get our uh what whenever we do fetch something by ID right we what we'll do we'll do request do params sorry we'll do request do params do ID remember we have used this so this params we usually pass in our uh URL right so we'll do let's say SL API SL product slash 1 2 3 4 5 so this is the ID that we'll be passing similarly here also when you'll requiring single product you need to pass the ID right so how we are going to pass it so here I tell that okay this will receive a ID parameter and this ID parameter will have a type which will be
ID now again this IDE is nothing but what this IDE is the unique identifier and here in this case this will be this 1 2 and three something like that and this also will be mandatory sorry and then I'm going to pass the type so type will be what type of product so this product let's comment it so this is our two queries and then we will be having the mutation so mutation is where we'll be able to create create a new product but that we are going to see later for now save it and now I'm going to Simply do module. exports and I pass the type definitions now I'm pretty sure this will be clear for you how we have created type and how we have created query now how we are going to get it right so we need to somehow call this query so for this one we are going to create methods right and Sim uh that concept here we called as resolvers so we need to create create a resolver files yet so inside this graphql I'm
going to create a resolvers do JS and this will simply resolve what you are going to do so how you're going to face the data okay so now here I'm going to first we need to get our products which is the dummy products currently we are having we don't have any database or anything so I'm going to get the products so this will be reer and let's go to data and let's go to products now I'm going to create our resolvers so I do resolvers and here we are going to pass the queries so now I'm going to create a query okay so I'll create our first query and here we'll be having two queries so one will be to get the list of products and one will be to get a single product so I'm going to pass here products so this what this will return so for now we don't have any database or anything so I'm going to simp simply return these products right as simple as that so now this will resolve or get the list of products for now I'm not going
to do anything else here okay let's save it and I'm going to show you that how we are going to run the server before writing some other things so I'm going to just export it and now let's go to our server.js and we need to create our or start our app server so I'm going to do here const and let's do this on app sorry first we need to get it from reare and here I'm going to get the app server also we need to uh because we are not using any Express or anything right that also I'll show you that how we are going to do it using Express but for now we are going to import another uh method that will called as Standalone server so I'm going to import one more thing from we'll do require and this will be Appo server SL Standalone and this will give us a start uh Standalone server method okay now here I'm going to also import our Appo server and then I need the two things the first one will be my types the
second one will be my resolvers so I'll go here and then I'm going to get type depths so I'll do require and let's go to our graphql and schema then I'm need our resolvers so this will be sare so we'll go to graphql SL resolv now I'm going to create a function so as sync function and I'll do start server Now to create a server it's very very simple so you just need to call this create a new instance of this app server and just pass both the things or config you can pass the first will be your types you can pass see and second unit was the resolvers right you can see and also you can pass other things like plug-in and everything that I'll show you in the next part so this will create a server but this will not work until we start the server right so here I'm going to now get our URL so we'll get something so I'll do have it and I'll call the
start Standalone server now this will take the server that you need to that you have created so I created the server now remember you need to pass these type depths and the these resolvers so here we are going to get or pass the server and here we are going to listen to a port so I'm going to pass a port and let's run this one as 4,000 now this will give you a URL okay and let's log this here so we'll do log and I'm going to do this on as server ready at and I'll pass this URL I still this will not work because we are not starting this so I need to invoke it so I'll invoke this server so now this will create a server Appo server will be running and I'll just simply do npm run okay sorry let me clear it so clear it uh so do npm Run start let's see what is happening see this will automatically run now you'll notice one very
interesting thing that what will happen if I go here so if I click here sorry if you're getting any background noise I think some people are talking and everything so you can see that you'll be getting a pre and this is handled by app and you can see that we are getting the queries and everything for now I think this all I already created previously something let me just remove all of these and now I am going to show you that how you're going to taste it right so first you need to give a query right and here you see that we have two queries one is to get the products and one is to get the single product and if you go to our let's say I'll go to my resolver so for now we are only returning the products so I'll get call the products and now see it's already giving all the options like okay this product will have a title it will have a price it will have instock it will have a ID and it will have a category what are the fields you need let's say you'll tell that I only need Title run it you're getting all the titles and this is coming from your dummy data now okay now it tell that okay I also need the category so now run
it it will give you the category you also need the ID run you'll be getting the ID see it's awesome it's really really really good so let's I need the in stock I run it and what else we are having also you have a price and I'll get the price so this means you are just simply quiring you're passing this and you are telling graph kill that okay give me all the fields that I actually need and based on that it will structure the data and it will return back the data I hope you're getting so now with this I'm pretty sure you will be able to create the this resolver so one resolver we created to get all the products now pause the video and try to create this resolver where you'll be getting a single product and then you need to pass this ID as input and then it will filter and it will give you the single product so let's do this one in the next part so let's create one more so now I'm going to create the product one so I'll do product and here what we need so we need the ID right so which I'll be passing as input and here simply just we'll do
products do find do item and I'll do item. ID should be equal to equal to this ID that we are having here that's it so now let's save it all right so let's go here and let's create one more query so I'll give a query here and now see if I type product and you can see that's already giving size and that you need to pass the product ID so here I'll pass the product ID let's say one and I'll tell that okay now I give me the title of the the product ID and I run it and see that we getting laptop if I pass two here run it you are getting coffee if I give three here we are getting s and also you'll be able to add other properties also it will give you the results all right so this is how it is working now I want to do one more thing I think we have run that script uh start folder right uh start script right let's do one thing let's run the node one I forgot to do that all right so this is fine so now what we'll do so now we know that how
you can create queries so now we are going to write our mutation now again when we be writing the mutas and first we need to go to our schema and I will add my first muten so let's add a typ and here I need to give mutation and here what mutation I want to create first so first I'm going to create a create product mutation so what this will do this is like add product controller so just like in the previous section we have done right so this will be a create product and now here it's very very important you need to tell that what are the things you will be passing as a input now remember when you're creating something new let's say product or something you usually do request. body and in that request. body you'll be getting all the data that whatever you're passing from your front end something like that so similarly here also you need to do tell and this will be a type of product because we are creating a new product so inside this what are the things we need to pass so first first I'll pass a title which will be a string right I need to pass a
category which also will be a string I also need to pass a price which will be a type of float and also I need to pass a inst stock which will be a type of bolean all right so this is our create product mutation so I'm telling that these all the fields I'm going to pass but how we going to write the resolvers so we need to go to resolver files and now I'm going to create our mutation here so I add a mutation and let's add our first mutation which will be create product okay now here again you need to pass all the things that you need to pass to create a new product and you see that we need to pass this title category price and uh in stock so these all the things will be receiving so I'll receive a title as input we'll receive a category as a input you will receive a price and also you're going to receive a inst stock so these all the things will be receiving and after this you're going to
create your new product so here I'll do const new product or let's do this on as newly created product and this will be ID sorry and here you're going to pass the ID so ID I'm going to do a string of products. length plus one and after this I'm going to do a title I'm going to pass the category I'm going to pass the price and also I'm going to pass the inst stock so these all the things I'll be receiving and based on that I'm going to create a new product after this I'm going to push this new product in our static data because we don't have a database for now so I'm going to do product. PST and then add this newly created product and simply return the list of products back so I'm going to return sorry return the new product back so newly created product so now this will create a new product mutation and if you go there right and let's refresh this now I'm going to create one more
and here you need to pass a mutation and now you'll pass a create product and see it is telling the these all the fields I need so now I'm going to add a title so let's give this one as let's say uh I'll do new product added category I'll give this one as Electronics price uh we'll give this one as 500 and in stock I will do this one as true once we'll do all of this let's I need all the things so I need the title I need the category of the new product that I'm creating I need the price also I need the in stock that's it and now let's run it and you can see that you're getting new product is now added you're getting Electronics price you're getting instock is true and now just go back to this here and also I think we also will be getting the ID here and if I run it we'll be getting id5 which is okay and then now let's go here and let's run it
and see what is happening now if you notice there is two more products is added because I run that mut two times that is the reason and you can see that you're getting the updated data back now let's go here and let's say I'll pass here five and I'll pass run here see you're getting the new product added right so this is how you are creating a new mutation right so this will be the process so now let's say how we are going to do some other let's add some one more mutation right so let's do a delete mutation here okay so go here and let's add one more so I'm going to do here delete product now again delete product will also receive ID that which product I need to delete and this will be mandatory and here I'm going to return a Boolean okay now let's save it so now again once we'll create the schema now we need to create the resolvers so let's go there and after this I'm going to create delete product so to delete product so this will receive a ID
and here we'll take const index and this will be products do find index we'll do product and I'm going to check if the product do ID is equal to equal to the current ID that we are having and if the index is equal equal to minus1 that means we are going to return simply false that this product is not present or Els we are going to do products do splice and I'm going to splice with this index and remove one item and at the end I'm going to return true that's it so now let's save it so now let's go there and first I'll go to this and run run it so you're getting three and now I'm going to add one more product here so run here and let's go back so now we getting four create one more mutation so I'll do mutation and I'll do delete product now
again we need to pass the product ID so I'm going to pass this new product that we have created which is IDs 4 so I'm going to pass IDs 4 and now let's run it and let's see what is happening so we're getting true and now if you go here and run it one more time you're not getting that uh newly created data right so it is working fine so this is how you can do a delete now let's go go there and let's add one more and this time I'm going to add a update product so now I'm going to do update product so do update product and this update product again see whenever you'll be updating something you need to again you can update the title or you can update category you can update price or you can also update in stock doesn't matter right and also it's not like you will update all the things at a time but how you are going to update normally how it will work in the previous section you seen that you need to pass the ID of that product that you want to update so ID will be mandatory correct so here first I'm going to pass the type as
product and what are the things we need right so we need the ID so ID which is mandatory then we need all of these four things so I'm going to copy this and paste it now again title is not mandatory all these are not mandatory so whatever you want to update that you can update so this will be your update product schema so you're pass you're telling the I pass the ID and based on that ID I want to update something okay now let's go to resolvers and let's create a update or let's do it after create or let's do it here so update product so again this will give you the ID that you'll be getting and also the other updates so I'm going to spread it now here I also need the index I'm going to copy this so if this index is minus one so I'm going to return
null or else what I'll do simply so we do const I'll do updated updated product and this will be our current product so do products of that index and these will be the updates that what we doing let's say the title is currently one and you are changing to two so I'm I'm overriding the title here and then I'm going to spread these updates and these all are normal JavaScript Concepts right there is nothing to discuss here so this will be my updated product and after this I'll simply do products of that index will become this updated product and then I'm going to return the updated product that's it now this will update the product now let's see if this is working so we'll go back I will create one more mutation and I'll pass updated product and if you notice that we are having this updated ID which is mandatory so let's say what I want to do I'll pass here one so first product I
want to update where title is laptop so I'm going to change this one to desktop so I'll go here and then I'll make the title and I'll do desktop and let's return all that so I'll return title I'll return the ID I return the category I'll return inst stock and also I'll return price so means only I'm changing the title and let's run it now see what is happening you're getting now title one and all the other things haven't changed and if you go here right this time it is leftt run it see this is changed to desktop awesome so it's working fine now at the end uh we have actually completed all the crud applications right all the crud Concepts that how you can create how you can fet how you can do fet by ID and also how you can delete by ID so what will be your homework right so you need to practice these things multiple times because see I'm already like I I know that I'm repeating these things multiple times but if you work on very very large application also right see at the end
all of this is kind of a crowd application so if you are able to master these card Concepts right it will be very very easy for you to work on complicated projects also so that is the reason I'm again repeating once again that try to create these projects by yourself once you'll practice all this multiple times at least five projects you need to create and after this only after that only move to intermediate or advanced level of Concepts so now with this the basic part is done so what will be the next step so next step right what I'm going to do simply because we are using dummy data for now so I will do one thing right uh so I I'll just inform you that what I'll do and then we'll come back so inside this right I'm going to create two folder one will be basic concepts and second will be project and what I'll do right I'll copy the whole content of this into the projects because the code will be exactly same the only difference will be in the queries and the mutation instead of using the dummy data we need to now interact with our database so that is
the only change and that I'm going to show you that how we we will be doing so let me just quickly organize that and after that uh we are going to start working with the databases so everyone now uh whatever projects that we have created so you can see that I just created uh one more project here and inside this I copied the same code and here we are having all the dummy data and everything but this time we will be using uh real database right so for that one I already created one database and we are going to use this one but before that uh let's do one thing let's quickly install uh this EnV package I'm going to install so we need to in install mongus also here also I'm going to use EnV and I think these two will be fine right so now let's install and then I'm going to create a EnV file here and I'm going to give this one as URI which will be equal to let's go here copy
this and I'm going to just paste it here and then also I'm going to use the port as 4,000 now let's go to our server.js and then I'm going to import so do reare env. config okay and after this I'm going to use this one as process do EnV so Loop process Dot EnV dot port and I think this is done so now what we need to do first right so now first you remember we have this uh dumy data and then we are using all of these but this will not work right so we need to create the models so now we are going to create our models which will be our model and here I'll
create product do JS and let's create this one so what other things we'll be having so here uh so first I'm going to import mongus and this will be require mongus so we do const product schema so this will be new mongus do schema so I'll be having a title so here this will be typee as string and dord will be true now let's copy this and we'll paste it so this will be category next I'll be having a price next I will be having inst stock now this will be type of Boolean and for this one this will be
type of number now let's save it and now let's export it so do module. exports and this will be our mongus do model I'll give this one as product and I'll pass a product schema and this is done now I'm pretty sure this we don't have to discuss we have done this on multiple times now then where we need to change it so we need to change everything in our resolver so if you go here right we are getting everything from here and we are creating and passing D data now we need to replace all of this with our database connection also before that we also include our database Connection in our server.js so let's start first create our data uh DV connection here and after that we'll start working on the resolvers all right every so now uh let's create one folder here so I'm going to create let's give this one as uh database and let's create db. JS so I'm going to quickly create this
we'll do mongus so we'll do require mongus and then we'll simply do const and I think till this time we have done this on I think so many times so that is the reason I'm not explaining all of this now so we'll do try catch so let's log this errors so we'll do console. error and we'll do connection field okay and we'll log the error and we'll just process the exit so we do process do exit in the try we'll simply do a it mongus do connect I think uh we already have the EnV file and here we are using this so you can simply use the same right so here we'll do process do EnV do let me just copy
it and that's it and then I'm going to just log here that mongod connected successfully now let's quickly export it so we do module do exports connect to DB all right so this part is done so now let's go to our server.js and we can simply where we are creating the server just simply call that right so it's pretty simple so I'm going to do const and let's do connect DB so we'll do require we'll go to I think what is the name that we have given oh sorry sorry I think we are doing this one outside of this okay this I made mistake let me let me just do one thing I'll just uh move both in Source folder same I'll do this one also so move this one to Source folder all right so now let's quickly
import it so do database and we'll do DB and just simply call it here right so we'll do AIT and we to connect to DB now let's see what is happening so I'm going to just save it and so mongodb is now connected successfully all right so this is done so now what will be the next step now as I already told you we need to start working on the resolvers right because there we are using the dumy data so we'll start with the first one first one will be very very simple now here again we no need this uh products uh here anymore because we we need to get the product model instead of getting the dummy data so simply we'll do require and then we will go to models and then I'll need the product now how we'll get the products I have I think we have already done multiple times so simply now again very very important we need to convert all of this
to async Method now and here simply do AIT and simply get this product do find so what find will give this will give you all the products correct it's very very simple now I'm going to comment out all of these for now same I'll comment out this mut also but because first time we need to see what is happening here let's save it and also uh let's not comment out this one because we need at least one product so I'm going to keep this create product so this I'm going to create so for now I'll just comment out these two all right so how we are going to do create product now again create product will be also very very simple so let me just remove it from here and I'll do one more time so we do create product this will be async now again here you are going to get we'll take the arcs and then simply just do const we'll do new newly created product and here I'm going to do
new so I'll get product I'll pass this ARs and simply sorry simply I'm going to return so have it and what we need to do newly created product do save remember we have the save method that we have learned in the mongodb section right and that's it so now let's save it and now let's see what is happening here so I'm going to now refresh this so let's go there and then I'm going to create one mutation and here we'll be having create product mutation so now I'm going to remove this and I'll just add all of these so we do my first product category will give let's say sports price will give 15.5 and in stock I'll give as true and
now let's say I need to get the title here so now I'm going to just run it and let's see what is happening so we getting my product here now let's go here and now let's go to browse Collections and let's see what is happening see got products right awesome now you're getting title product and everything in stock is true now let's go here and let's go to the first one now here simply we'll do run see what you're getting you can see right we are getting title category sports ID in stock and price now see this is not a dummy data now anymore this is a new data sorry this is the updated data you are getting from where from the mongod database so let's try one more time go here and I'll do second product added second product let's make this on electronics and I'll do let's say
1,000 and I'll do this one as false now let's run it it's added and now I'm going to just do refresh we getting two products and if you go to the first one and run it now you'll be getting two products awesome so now this is done next thing what we'll do we'll get a single product now single product will be very very simple see here this is nothing new right when we have created the controllers using the rest API development you are creating the controllers and inside of that you are using this method and now here you are doing nothing you are creating resolvers and then you are creating query or mutation mutation means where you are creating or writing any data and querying means where you are querying or fetching any list of products or data whatever you you are getting so now I'm going to just let's remove it so we get product and this will be again a sync method so what we'll get we'll get the ID right so we need to pass the ID here
and here I'm going to do have it and we'll do what product and then what is the method we need to use find by ID correct and here what will pass we pass the ID this ID and that's it now let's save it now let's go there and let's do one thing we need some ID right so I need this second product ID so I'm going to copy this and we'll go here and let's I'll pass it and I need the in stock as well as I need the price and now let's run it see awesome you're getting the second product now if I go and copy this send it here you'll be getting the first product all right so now this is done next uh we have created two and now I'm going to create delete and updated product so let's uh start with the update product so I'll create update product now again uh when I'm doing all
of this right again I again I'm repeating that try to uh write all of this by your own without watching the video means you can pause it and then if you're not able to do it then only you can see it so here what will get we'll get all the updated values right so updated form values or whatever you can give we we'll give fields and here I'm going to Simply get sorry return we do have it we do product and we'll do what find by ID and update remember this method and what this will take this will take the ID that which product you want to update it will take the method uh sorry Fields so here I'm going to pass the fields right and then we'll return new S2 which will give you the updated data back and this will be pretty simple that's it now let's save it now let's go here and let's say I want to update this my first product to my first product edited so I'll copy this and uh what I'll do okay let's do one thing let's create one more here
although we already have but I want to create it so we'll do mut and I'll update product and here let me just remove this so I'm going to pass the ID so my ID will be this ID and I'll pass the title will be my first product edited successfully and then I want to get the title I want to get the instock I will get the price also get the category so now we are telling the to go get the ID with this get the product with this ID and return and update this product sorry title from my first product to my first product edited successfully and give me the result back now let's run it so now my first product is edited successfully let's go here uh refresh this it's already updated and even if
you go to the first step you'll be getting the updated data right awesome and now I 100% sure you'll be able to do the delete product because delete is also very very simple so let's do delete product and this will be also as sync so we'll get the product ID by what uh by what we need to update means using this ID I will update that uh sorry delete that particular product so I'll do const and let's do result so we do AIT and I'll do product dot find by ID and delete remember this one and just pass this ID very very simple and then what I'll do right I'm going to return this result or let's do this one deleted product all right so let's return this deleted product and now see if it is working or not so I'm go here I want to create one Moree so I'll do third
product and this will be kids and I want to run it so you'll be getting third let's go here we're getting three products I'm going to copy this create one more and then I'll do a mutation I'll do delete so this will return the ID and simply pass this ID here that's it run it delete product this is true and if you go here right run it now you'll be getting only two products even if you go in and refresh this page you'll be getting two products now with this we have completed the basic level of understanding that how you can integrate graph key with nodejs also how you can create schemas how to create queries how to create mutations what you will do I'll highly suggest do this so what you can do right simply create two three projects and instead of doing the similar functionality whatever you have
done try to apply something else right so for example in our rest apsx and we have done some filtering and sorting so those things you can try to apply here now why I'm telling that because there is nothing related to graph C right it will be simple how you have done while doing the rest full AP development so try to add some more functionality and then after doing two three projects it will be habituated and it will be easy for you to understand all right so that's all for this particular section now let's move on to the next one all right everyone so welcome to a new section so in this particular section we are going to see how you can use typescript in nodejs now before starting uh this particular section I want to uh like mention one point very clearly is that this also will be very beginner level of uh section we are not going to cover each and everything okay I just want to give you the idea that how you can start your journey and also it will be really good if you know some of the concept of typescript right because I'm also are not going to cover
each and every typescript concept here this video will uh length will be very very large and it will be really difficult so what I'll suggest that please go to the official dock or or also you can watch some of the videos that are available on YouTube and then you can come back to this particular section but to start your journey with node and express whatever things you need to know that we are going to cover for sure in this particular section but first What I've Done Right I created a blank folder here you can see that the first thing we need to uh set up a new typescript project and we are going to see how we are going to do that the first thing is that you need to initialize a new node project right so how we usually do that so we'll do what npm and then we'll do init hyphen y so this will install package.json and now we need to install some of the packages so what are the packages we need so we need to install typescript we need to install the types of node and also going to use another uh module or package that is called TS node okay so these three
things we are going to do now you can see that this TS node is just a typescript execution engine and this is actually what it does that transform T typescript into JavaScript and also enable you to directly execute typescript on the nodejs without precompiling this is important now one more thing you remember in the previous section we have done node one or something so similar way we are going to see that how we can use this TS note to run our entry point which will be our server.js or index.js whatever you'll be creating but before that first we need to install all the packages I'll do npm install and let's install typescript then we're going to use types from node also I'll use TS node and all three I will save as a de dependency because this we only need uh when we'll be doing the development now once this is done so now I'm going to create a source folder inside our root here so let's create a source
folder and inside this uh let's create our first file which will be index let's give this one as app. DS all right so now I'm going to log here so let's log sorry why this is coming let's do this one as hello node js from typescript and let's save it so now what we are going to do next step will be we need to create our typescript configuration which is the file called as TSC config.
js and there you are going to configure all the properties and everything you need for this particular project and how we are going to do that now to do this one let me just expand this so I'll do clear and we're going to use this m npx TSC and I'll do in it now this will create a TS config.js and here you will get quite a few things that you need to check let's go here and you can see that you're getting some of the things for example it's using the es6 then uh what else we need if I search for module I'll see that it will use definitely so you can see it's using common J right then we having lib so this also I want to comment out and I want to use here es6 next uh what else so we also need to check what is our output directory and what is our root directory so in this output directory is nothing but whenever we'll be building our code right so this
typescript will be converted to JavaScript and I want to store I want to tell this TS config.js file that in which path or destination I want to create it so let's say I want to create it inside a dist folder so I'm going to give this one as dist similarly for root directory so here I'm going to give this one as/ source okay so this uh things we need then let's search for strict so strict will be true and also I think rest other things will be you can keep it like this okay whatever things are there now this is uh these all the things that you need and also we need one more thing and that is let me just copy all of these we need to pass that what are the things we need to include and what are the files we need to exclude so here I'm going to cut it and let's create and paste it here and now okay I think there are some error that
we are getting okay oh it's already there okay let me just remove it okay so I think we need to I mismatch with this pH after this we need to do it so I want to tell that okay what are the files I need to include so inside source every file I need so I'll go to source and then I'll pass this next I will tell that what are the files I need to exclude so I don't want to exclude my node modules so I'll tell that okay exclude the node modules now if you have test file in your project so you also need to specify here all right so now with this this TS config.js and configuration is completed now what will be the next step Next Step will be that we need to write some of the scripts and based on which uh we are going to build our code or run our de server so let's start with our first script so first uh script will be the build script for this one I'm going
to use TSC and next this build will simply convert your JavaScript sorry typescript to JavaScript code then I'm going to do a start script so start will be node remember we will create a dist folder right and inside this we'll be having app.js so this will be app.js and next we'll be having Dev so here we'll use the TS node package that we' have installed and here I'll mention that okay go to source and inside run this app.
TS file so this will be our Dev so now let's save it and now see what will happen if I now open this and let's clear it and I'll do npm run sorry we'll do npm run Dev and see what will happen we'll get that console so getting hello node just from typescript awesome and now if I now clear it and let's build this code so how we are going to build it we'll simply run npm run build so we do npm run build and see what will happen there is a dis folder is created and if you go there right you see that whatever you're writing in this TS file that will be compiled into a JS so let's say I'll go here right and I'll do something like this so let's say there is a function G name and this will return the name now
this name I'll pass here now definitely here you need to pass the type so let's I'll pass a string here and I'm going to just simply log this gate name and let's pass so definitely if you pass this it will give error so I I just want to show all uh this uh all the points so that is the reason I mentioned that you should know some of the very Basics that how this usually work definitely I'm going to also discuss all of this in the next course I'll pass this here save it now let me just clear it and I'll run this npm run Dev first so you'll be getting my name definitely here with this hello world and now I'm going to build it one second and we'll see what is happening so if you go there right now see there will be a function also is added right so this is what I just want to show you that how this build is working now if you want to run this compiled JavaScript so what you need to do so you need to run go to to package.json and there is a start script
so start script is simply running your dist and inside this you are having app.js so what you'll do you'll do npm start that's it and it will give you the same result you're getting the same result right so that means the setup is now completed so we've done quite a few things the first thing what we have done we install all the typescript related packages then we'll go to we created our TS config we go to package.
JS and we created our script and based on that we are compiling the code from Javas typescript to JavaScript so this will be the very basic way how you can set up your typescript in your node application now let's move on to the next part all right so now let's learn some of the basic types in our typescript so what I'll do right I'll just remove all of these now and only keep this console log and let's do one thing so here what we going to do right I'll give this one as basic types and then let's start with the first one so first we'll start with Boolean right so what we'll do usually in our JS so we'll do let's say let and we'll do is done and I'll make this one as false now here this is a type of volan that is fine but in Javas sorry in typescript you need to specify this type right so how we usually specify the type of this particular variable so after this you need to give coland and now you
need to give give Boolean right so now this will understand this is a type of Boolean if I pass a string here this will give you error that you can't uh assign a Boolean value to a type string so I'm going to pass a Boolean here so that is the first thing next uh we are having number so let's say if you have a num which is 100 so and you are giving here let's say number so this will work but something other than number it will not work I know these all are the very basic type of things I'm pretty sure you already know but I just want to quickly go through all of these so that it will be easy when we are going to uh dive into this Express and those things next we I'm having string so let's take one string and I'll take my name and this will be type of string correct now if I now remove and make this on number it will not work similarly if you give array it will not work object it will not work so there is
a type check for each and everything that you'll be doing inside your typescript all right now next we are having array so for array what we can do let's say you are having a list and here you having array of 1A 2 comma 3 now if you H here right if you see it's already you will take a number this number is a array so it's array of numbers correct now here what you can do simply you need to give or tell that okay this is a number and this will be array right if you remove this it will not work correct because this is not a single number it is array of numbers you need to give this empty array with the number type now what will happen if I just give this so see it will not work right it it is telling that you can't assign this string to a type number next what else we are having let's say we are having another type let's say I'm having some uh products and this will have a product one then I'll have a product two and
I'll have a product three so what is the type if I over here right so this is array but this is a arrow of what this is Arrow of string correct so if I over here you see that this is a string and this is Arrow of string so how you're going to do this so let's say I'll take a string here and pass it it will work or you can also do like this so you can simply take a array and you can tell that okay this is array of so inside this you need to give the type so you're telling the this is array of string both will work all right next what else we are having so let's take uh okay let's see another type which is like any type so any type means whenever you have some variable let's say I have some random value that I don't know what is the type of this particular value so in that case I can give this one as a type any right you should not do this one actually it will be very rare it's you should always give the types and everything and this
is a let's a type of number I'm giving now what will happen right if I just do this on this random value as a string it is not giving any error you noticed now I'll do random value is true so it's G Boolean and then after this I'm giving random Valu is now array so it's working because it's don't know the type so you're able to assign to any any type of variable right uh so what will happen if I just simply make this on number see you're not able to assign right so that means whenever you'll give a type of any that time you can assign this variable to any type that's it now what else we also have a type of null and undefined so let's say you have a variable some XY Z and this is a undefined right so you can specify the this as undefined type so this will be undefined type similarly for null will be it will be null type so we do let's say y z some random value and if it is a
null so you can specify this is a null all right now you can also assign some enum enum means so let's say I have a m of color and this can be a type of red it can be a green color and also it can be a blue color and if you want to use this so let's say I have a variable which is D and this D will have a type of this enm means this D can be only color red it can be only color green or color blue so I'm going to pass this color as a type and now if you see I'll do color and if I do Dot and here we'll be getting this either it can be red or it can be green or it can be blue sorry it can be blue but what will happen if I give something else some random value so this values doesn't exist it will give you error so this property doesn't exist
on this type of color right what will happen if I just add a g here it will work right so this is how you can also so give an num and let's make this one which one will do green that's it so I think these all the things at least you need to know to start with so we have a uh type of uh this Boolean variable number string how we can use array of numbers Arrow of string what is the uses of any and the undefined type of null and also how you can use enm all right so now let's move on to the next one now again I'm I'm again repeating once again multiple times that this is not the everything right this is just a very very basic things there are huge huge lot of things like typescript is a very I'm pretty sure that some people might disagree with me that typescript is easy actually it's not you need lot of practice so that's why why I'm repeating every time that you need to go to the officeal do and try to practice by your own it's very very difficult to cover each and
every concept within one particular video and I hope you are going to understand what I'm trying to say right so that is the reason I'm doing very very minimal things what exactly what we need for this particular node J app but again there are a lot of things to learn here all right okay now one more thing I need to show you what is called the concept called tle I don't know how it pronounced so let's say I have a variable here and I'll do ABC and this can be have a string also it will have a number so this is also possible and here I'll pass let's say high and I'll pass a number as 500 or 400 see it will work but if I give this right it will give error and then what you can do simply you can log this it will give you the result so you can also use like this or asign variable like this so this is all about the very basic level of types now let's move on to the next part all right so let's quickly see now uh that how we
you're going to use interfaces and also types so what is actually interfaces right see interfaces Define the structure of your data or the saes for your data let's say I have a user and uh and this user will have a name property this will have a ID property and this user will also have a email property right and let's for suppose this email property will be optional property and there is another property which is like uh let's say created at means this user is created at what time and this will be a readon property means you can only read it you can't change this value so somehow you need to every time you create a new user right so you need to validate whether the type of that user whatever I'm creating if it is correct or not so to do this one in typescript we can create custom types or saves for our data and to do that what we are going to do is we need to use the interface keyword and here you need to give the name of the interface so here
I'm going to give this one as user okay and inside this I'm going to give that okay this user will have a name property and the name will have a type of string because it will be string value then this will have a ID property this also will be a type of number right and this is mandatory property now as I already told you that this user will also will have a email property okay but this email will be a string but this email is optional property right so how we are going to do optional property and to specify that this email is optional property we need to give this uh question mark right so now this email will be optional property and how you can do a readon property so give readon and then you need to give the uh field name or the key name so in this case this will be created at and this will be a type of date okay so this this is how we so first this is a mandatory property this is optional property and this is a leadon property right so now let's say I
want to add a user or I want to log a user so this user again just like you previously we have given the type uh like what so for example if it's a string will give string if it is a number will'll give a number if it's a Boolean will give a Boolean so in this case here we are going to give as this user because this user has a custom type of this interface user so here you'll give user and now let's I'll give name which will be suum and you can notice one thing is that you are still getting this error and the reason is because there are two mandatory Fields you have given only one which is name but the ID is still missing so you need to give ID property so let's say I'll give ID of one but still you are getting the error why is that because this ID is a number so you need to give a number prop value here right and you can see that still you are getting error the reason because although this is readon field but this created at is a mandatory property so you need to give this value so I'll give
a create a DAT and this will be let's say new date and now the error is suddenly vanished correct and if you notice one thing because this is optional property so even if you don't pass it it will not give you an error so let's say I'll pass email then it's okay that you can pass it like ABC gmail.
com but I'm telling that if it's a m optional property so it's absolutely not necessary that you need to pass it so this is how you can create interfaces right now next you can we can also create types right so that we call Simply type allies definition so let's say I'll have a type something like this I'll have a type and this will be a type of product and here this will have a for example this will have a title which will be a string and let's say this will have a price which will be a number right so this is how you can give types and then you can create a product here so this is like there is not that much difference between interfaces and types So based on different scenarios you will be able to use this either types you can use or interface also is very common common to use so now let's say I want to use a product one so this product one will have a type of product and now again here you need to give the type sorry title and this will be product one and
also you need to give a price which will be 200 now you can see that the error is vanished right you are not getting that error all right so this is about uh the very basic of interfaces and types now what will be the next thing so next thing we are going to learn that how we are going to see one more thing we need to discuss and that is the modules right so in the beginner in the beginning of this particular video I already told you right that you should have some idea on the JavaScript part es especially the es6 module import and Export so till this part we have learned like okay uh to export a module we will do module do exports correct this is what we'll do and to get it we'll usually do like require but now in es6 what we need to do here we usually need to do module. export instead of this we need to export a module and for require we need to do a import a module and I'm not explaining this one very properly because I'm 100% sure you already know till this part that this will be the only difference all right sorry now we are going to understand some of the function Concepts
right that how we can create functions with uh so let's start with this one so we do functions with type annotation so what I mean by type anotation right so let's say I have a function uh this is ADD function and here this function will take two numbers as a input and at the end you will return the multiplication of these numbers so we'll do a into B but here you'll see that you every time you'll use some variables or something you'll get this error because you are not specifying the type here so now I want to give that okay this a has to be a number and this B also has to be a number but you can also specify that this function is returning a number if you notice it's a into B so you need to specify that it will return return a number here okay if you do a string right you'll get error as simple as that
so whatever you are doing oper and based on that you need to give Tye so I'll return a number here okay so this is how you can do function with type annotation now let's see how we can do in Arrow functions so to Arrow function it will very simple so let's say okay why have given this one add so let's give this one multiply because we're doing multiply here and now I'm going to create add function okay now let's say this will return num one plus num two and this it will receive as input so receive num one and it will receive num two but again you need to give the type here right so do number num two also will be what it will be also number and at the end it will return a number as simple as that okay so this is how you will be doing with uh Arrow function now let's say there is one more other function is there and this function will greet a person right and now in this function there can be optional property also so how we learn
that we can use optional property so we need to give this question mark right so let's say this will re get name which will be a type of string and it will receive a greeting right and this greeting will be optional so now I'm going to pass here question Mark and then I'll do that this also will be string and at the end this function will return a string so I'll give a type a string and what we need to return so let's say I'll do something like this that it will return this name and also it will return return this greeting okay so now you notice one thing that if I just log here right and let's say what we're going to do we'll do call grid and I'll pass pass my name here and you can see that we not getting an error the moment I remove this so now we getting error because now this is a mandatory property right and if you pass something here let's say hello then also you'll be not getting because anyway you are passing both the
things so this is one more thing you have learned right so now what we have understood so far is that whatever function you are using and whatever inputs you're using what is the return return type everything you need to check and what whatever you're using as input you need to specify those types all right okay so now we know that how to use functions also and modules part I already discussed that we need to use export and import and now what will be the next thing so in the next section we are going to start working with our main thing which how we are going to set uh this typescript noes with Express so let's start working on that particular section all right so now uh we are going to see that how we can use Express JS or how we can set up Express with typescript in nodejs right so what I'll do right I'll just comment out all of these or I can do one more thing is that let's create one more file here or let's create yeah I think file will be uh better so do Basics dots and then I'll just cut it all of this from here and
then paste it here okay now first uh to use express we need to install some of the packages right so what are the packages we need the first of all again we already have installed typescript now we need to uh install the types of Express also we need types of nodes that we have already installed we need TS node that we also have already install and also we going to install node mod so for now let's install node mod and also I need the types of Express okay so these two things I need now what else we also need to install typescript sorry we also need to install Express so do npm install Express all right so this is done so after this now uh let's go to our package.json
and here we are already having node dist and for build we already have this and for Dave what I'll do right I'll simply run node mod so that we don't need to start it every time and we'll save it and it will run the source / app. TS file only all right so this is done let's clear it and now we'll start working with the app.
TS file so where we are going to create our first basic uh API route or how we can use our Express right so first of all see I already told you right now in this case we are going to use Import and Export because we are using the ESX module so here I'm going to do a import and we need to import something so we need to import Express from and we'll import it from Express correct so first thing you need to import it then what we usually do so usually remember we usually do something like this right so we'll create an app and then we'll invoke this and here now every time you will be doing something you need to specify a type like it's always a better idea now I'll give you one more idea right how we usually get to know the types if you over here right you'll see it's giving a type so from here you'll be able to understand okay this is the type of exess because this is express application right sorry so this is express application so you need to give
a type of Express so here I'm going to just take Express and I'll just import it let's import this one so we'll import from here okay so after this I'm going to take a port so do const port and let's do this on is 3,000 and now I'm going to listen to this port so do app.
listen I'll pass the port and here we're going to do log and let's do server is now running on Port 3000 which is port now let's create our first API route so I'm going to do app.get and let's go to the homepage which is SL and then now I'm going to take what we'll take request and response remember and now I'm going to send something so let's send raise.
send and I'm going to do a Hello and I'll do typescript with Express now notied here one thing is that we have this request and response right now we need to understand that what will be the type of this request object and what will be the type of this response object and it is very very very important right so if we over here right you can see that we are getting all of this now you might think okay what the hell is this okay now here you see this will take so first of all what about this request and everything you are seeing right here you need to ID uh sorry you need to understand that what actually all of these are so what is the first object what is this any what is this any what is this squarey string and other things that I'm going to explain each and everything step by step first we need to give this one as a request so I'm going to import this as request object so this is the type of this request object here if you over here also right you're getting this request
so you'll pass it here this is the first step and similarly for response this will be response so I'm going to import response here and this will be the type of this now let's understand what is this request object on this right so I'm going to just comment out this request object will be so here let's say uh it consist of four things right not four things it consist of five things so if I type something like this so this request this will have a type something like this it will have a response body sorry so it will have a response body then it will have a request body then it will have the request query and at the end it will have some locals now if you H here also right you'll be able to see similar kind of structure right and you can see that you'll be having this request quy response body sorry request body response body and
this is the P which is nothing but the params now I will definitely going to explain what actually this is now remember whenever we're doing this right for example we are telling that okay this will go to the homepage similarly if I do another route for example slash user SL ID so I'm telling that okay whenever I'll go to SL user SL ID this route so this route is actually this type here that we are passing that this is the type for the route parameters first one what is the second one so second one is the type for the response body this is the response body so what response body is right so usually do something like this right r. Json sorry we'll do this race do Json here let's do Json or we'll do like rise dot send see here only we are doing right so this is that response body the third one is the request body okay that I'm going to explain later when you'll be creating different routes second will be request qu uh request queries request queries mean let's say you are passing some params some you are doing some
search or filter so that time it will be helpful all right and then we are having the locals which is the type for the response locals which is very rarely used okay not don't use frequently but most of the times you need to focus on these first four things so this is about your request now what will be the response response is simply the typing for the response object right now here I'm going to now remove this and now let's save it and I'm going to run it so now let's clear one more time and I'll do npm run Dev so server is now running now let's go here and let's say I'm going to create one more collection here let's do a blank collection and I'll do node just typescript so let's add our first request which will be home homepage and I'm going to just copy
something from here and we'll paste it here and we'll send it and we getting hello typescript with Express I think that is the one that we are sending back right so this is working fine now you might definitely think that okay this is extremely repetitive because these things we have done multiple times but that is not the point the point is how we are going to type each and everything because now we can't directly pass any type here right just like in JavaScript we usually do but in typescript you just need to ident identify and practice that what types you need to use in which scenarios so that is the main thing all right so you started with our first now let's quickly create some two or three more routes and then it will be like you'll be more habituated but definitely you need to create more and more projects on top of it so what I'll give you a best idea right whatever projects till now we have created in JavaScript once you'll complete this section try to convert those project in typescript right so that will be the best homework that you can do now let's move on to the next
part all right so now we are going to see that how we can use middleware and everything and also how we can use Uh custom interface for extending some of the middle wees that we'll be creating so first of all we need to Parts our Json bodies right so what uh middleware we use till now so we need to use the express.
Json that we have used multiple times right so first I'm going to use that so do Express do Json and after this what I'll do right let's say I have I have a middleware where I want to add some uh start time to my request object so I want to add a start time property to request object so how we are going to do that so now normally what you usually do we do app.
use right and here I'm going to do a request and now let's say in this request I want to pass a custom request property or interface so how we are going to create it right so whenever you will be doing any custom Properties or custom data saving you need to add that interface so how you will do it simply so we'll do interface and then name give some name so we do let's say custom request now because you are adding a new property in the request object so what you need to do you need to extend the request from the express that you'll be imported here right so what I'll do so I'll do extends extend what it will extend this request here and then simply just add a start time property here okay I hope you're getting but you need to make make this one as optional now you can keep this one mandatory also but in that case you need to pass it every time so here I'll give this one as number so this is let's say a custom property I added and here I want to pass it as a type so I'll pass this custom request okay then I'll pass
our normal request which will be our sorry nor normal request this will be our response and then we are going to pass our next now remember this will take a next function right all the middle we so what will be the type now for this also we have a type and this type is called Next function so this I'm going to import here so do next function so this will be my next [Music] function and here simply we'll just use uh this request that we are having right and I'm going to to this request that we are using here okay I think I've have done something wrong here okay this should be like this so this request do start time now you can see you already get the this property here and let's I will do current date so I'll do date do now and after this what we need to do whenever we use any middleware right we need to call the next function that's it but again I'm repeating these all are not
the point the point is how you are going to type each and everything right without it this it will not work all right so now let's say I want to create one more route here after this so I want to create a post route now in that post route what I need to do let's say I need to create a new user and that user will receive a name property and it will receive email property so how we are going to type it now definitely you'll be able to create the logic because that we have already done previous time but we need to understand how we are going to type it now remember I already discussed this request this type of this request right so what this will have so first it will have the type for the route parameter so for example let's see if you're going to user and then you're going to this ID so this ID value will be dynamic right so this we have already discussed so that is the reason this request again I'm typing here I'm repeating this things multiple times because I know for beginners it will be difficult so here it will receive first one will be the type for the route parameters like this then second one it will be the type for the response body response body is nothing but that rise.
Json or raise. send we usually send back the third one will be the request body request body is nothing but these request that we'll be getting right so remember when we created these controllers and everything we usually used to get these values from where request. body right so this is the type for the request.
body okay fourth it will have the request query request query means let's say you are searching something right after this you are giving some value and then you are typing or searching something or filtering something so that will be the request quiry type and at the end you will be having the locals so this is actually how you need to type it now let's how we are going to do it so let's I'll do a app.
poost and I want to do this in this user endpoint so now we need to start type so I'll do request so request will be type of request now the first one see here we don't have any type for the route parameters right because we don't have any Dynamic value so what happen first one will be empty this part right second that is for the response body so definitely it will going to be empty and what will be the third one now third one is your request body very very very important here because request body mean this is a post request so you'll be getting the data back from your front end so here you need to give some type right so how you're going to do the type so you need to create an interface and what will what will be there in the interface you'll be having the name and the email so I'll create an interface and I'll give the interface name as user and here this will have a name which will be a string and it will also have a email which also will be a string and this will be the type that
you need to pass here and if you over here right so this user is referring to this interface and this request will this request body that you're having right so this request board is nothing but this user interface now it will get that type that's it now once this is done after this we're going to pass the response and response will be type of response all right so once this is done now what we'll do simply uh we'll get our from request dot body okay I think we have done something wrong here let me just check see again this thing I'm doing multiple times so this will be uh if I over here right okay this should give me request. body yeah it's coming and if you type here right you see you're getting name and you are getting email so these two things you're getting from here awesome and after this what we'll do right
simply we'll do raise. Json and let's say I want to pass a message that user created and I'll pass this name and then I'll pass this email so now let's save it so now let's see if this is working or not so let's go there and I'm going to create one more so do add new user all right so this will be a post request and let's go and copy this and this will be user we go to headers and then so we need to use a content type so let's do a content type and this will be application sljs we need to go to body Go to Raw Jon is selected here and now here we are going to pass two things right so first I'll pass a name which will be let's say
my name and I'll pass a email which will be some email okay so now let's send it and let's see what is happening so you can see that user created and we're getting this result back again this is not the point the only thing is that you need to understand how we are typing here right giving types for each and every request and response and this you need to play around okay now what will be your homework here right so what you can do right simply you can create one more request request where you will be getting let's say you are passing some search query okay and based on that for example let's say you are passing some uh query to find the name of that particular user so you can uh check that or you can follow that process this process that how this type is working and based on that you can give the type here now next thing I will show you one more way that how we are going to do this typed uh route parameters right so for example let's say I want to create
one more where I want to get a user based on ID so I want to get user based by ID based on ID so how we are going to do it so here I'm going to do app do G and now you want to pass SL users SL ID now you see that this ID is a dynamic value and after this I want to again type it so I'll do request response and here so what will be the type so this will be definitely response and what will be the type for the request now now again it will be a request type and what we are going to do simply again see here as I already told you right now this time we are checking this part because there is a dynamic value and there is a type for this route parameters that we need to pass and what I will be passing here I simply passing that okay this will receive ID property and this ID property will be a string okay and what will happen right if I just go here right and let's say I'll do const and I'll simply do request do
params you'll see what will happen if I just do here you see it's giving suggestion ID that that means it is getting that okay this will now receive ID property from request. params and simply for now I'll just do. J and I'll pass the user ID okay and this user ID will pass this ID so that means now we have typed the first part now if you first part means the route param you have typed so you're telling that this will receive a dynamic value which will be ID and if you go here here and let's try to add a new request and I'll do a get single user let's go here and I'm going to copy this so this will be sluser SL1 this will be get and send it see what will happen okay we are getting some error cannot get okay this will be users sorry my bad so now let's send it so getting user ID 1 if I do 10 it will be user ID 10 okay so you're getting the
result back so this is how you need to use uh or set up Express and create routes now why I'm not creating any big project or anything because we've already done previously multiple times I just want to show you that how you can do the types and everything right and based on this you'll be able to create see this part what we are doing here right this is nothing but a controller right and that we have already done so what you can do right you can create a simple crowd application and then try to move this logic into your that uh controller file and then import it here and the rest of the logic will be same now I in the next part I'll quickly show you how you're going to create a uh mongus model using uh using in this typescript right because we already learned that how we can create models so but we we didn't typed it because in JavaScript we don't have to give any typ rate so that quickly we are going to see in the next part all right so in this uh section I'll quickly show you that how you can create or type your mongos or whatever models that you'll be creating for your database right so for
this one first we need to install mongus and the types for mongus so here I'll do npm install mongus so this is the first thing we need and the second part will be we need the types for mongus so we'll clear it and we'll do npm install at theate types slash mongus and this will save as a de dependency all right okay so now inside this what we will do right I will create a models folder and let's say I have a user model so do user.
TS okay so how we are going to do it see it's actually exactly same only the difference is how you are going to type it that's it so first we need to import mongus from mongus that is the first step and then what we usually do we do con and then we'll do let's say user schema and then we need to do new right and we need to import the schema so I'll do I'll import schema from mongus and here we need to pass all the properties like what are the properties that we need to pass let's say I have a name which will be string then I will have a email which will also will be a string then I'll have a age which will be a number and then let's I'll have a created at which will be date now here after this what we usually do we'll do const then I'll do user and this will be mongus do
model and here usually pass the collection name right so in this case let's say I want to give the collection name as user and then I'll pass the user schema now I know again I'm pretty sure you'll be bored by now because I'm explaining this thing again and again but because see we don't have any other option this that is the reason I haven't created any project because it will be extremely repetitive but we need to see how we going to type it now here again we do simply export and then I want to export the user and this model now I want to use in my let's app. TS or whatever controllers file I have created now how we are going to type it now see to type this one we need to import something from so that is the first step which will be document so this is the mongus document right if you over here this is the generic type for the document so what you can do you can create custom types remember I created this custom request and then I extend the request object from Express similarly for this one also you can extend the main document and then you
can add your own Uh custom uh schemas or user structure whatever you you will be creating here for example I let's I'll create an interface and I'll give this one name as I user so this is the name of my custom interface which will extend the documents extend documents means here I'm extending this particular document from and now here we need to give what are the properties that I need to get so for first I will have a name which will which will be a string then I'll have a email which will be a string then I'll have a age which also will be a string and at then I'll be having a created at which will be a string so you created a custom sorry this will be date and age will be number sorry my bad this will be number okay so now you create a all this so now you need to just simply use this interface so how you're going to do it
so you'll simply pass it here so I'll tell that okay this schema user schema that I've have created this is type of I user which is now extending the documents from mongus okay so this is done now after this similarly in this model wherever we'll be creating the model here also I want to mention that okay this will be type of I users save it and what you need to do now you need to also import sorry export this type along with this model and how this will work because this one you're going to use in your controller file for example let's say just give giving you the example now I want to use this user model in this file and then whenever let's say I will get the list of users so I have this uh getting the okay I'll create one more route here so let's say I want to get one more route so I look SL users and here I want to create a Asing method so this will be Asing method which will have a request and
response and this request will be type of request and this will be type of response and then here I'm doing some database manipulation right so I'll do a try and then I'll do a catch and let's say I'll simply send a status of 400 and I'll do a [Music] Json I'll do a message of some error ORD okay now in the try right what I'll do I'll get user and this user I'll get for example this AIT and this user schema that we are having right here so this I'm going to import so I'll import this user schema from model and let's say I'm simp doing do find and I'm getting the list of user but here what you need to do right you need to specify that what will be the type for this user so what will be the type this type will be nothing but this
type you exported here because this is the properties this interface includes here right this you have mention here so now you say that okay these users will be type of I user and this will be a array okay so that means this will be array of array of object because there can be multiple users and this is how you will specify the type here okay so this is the main thing I want to explain that how you're going to use the type and how you can create model and then specify the type while creating the schema uh whenever you'll be creating any schema now here the concept is so generic is that whatever model you'll be creating right at the end you need to apply your own knowledge because you are going to you are the one who is going to decide that what are the fields you'll be having here right right now I'll highly recommend now uh two things I'll tell all of you that try to create at least two projects and what you can do simply again I'm repeating whatever projects you have created in the previous section try to convert those using typescript and apply all
these Logics you have learned so far okay so I think with this I have completed this complete video I know you have learned a lot of things but again I'm repeating that I'm also telling this that this is not everything we have covered in this particular video because this is focused mostly on completely beginner level I'll create a part two of this where I'll be discussing all the intermediate and advanced level of Concepts also so if you find this video helpful give a like comment down and please subscribe to my channel I'll see you in my next video till then good luck and peace