Build a CRUD API with Nodejs and MongoDB in 10 MINUTES! | NestJS Tutorials

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so crud stands for create read update and delete which are the four basic functions of persistent storage of items generally an api exposes routes to execute these functions on a specified item or a list of items allowing the users to directly manipulate the data that they have access to and today we will be building such a system that enables the user to create read update and delete from a collection of dog breeds in our database and with the help of nest.js we're gonna be able to do this in under 10 minutes hello world my name is igor and welcome to my channel here you can find coding tutorials every week just like the one that you're about to watch so if you enjoy it please leave a like down below and let's get started now like you see on the documentation nest is a framework for building efficient scalable node.js server side applications and then under the hood it makes use of robust http server frameworks like express that we all know and love now one point to notice is that next js documentation is by far one of the best i've ever seen besides getting over the overview of what it is able to do it also has documentation on fundamentals that you can use techniques to implement on your application a specific section just for security of your app how to implement graphql web sockets microservices which nest js makes easy to use and that's why it's my go-to for server-side applications in node.js now firstly we can go into the first steps to see how we can set it up the first step is to run npm install globally of the next.js cli which i've already done before but if i haven't i would just type that command directly here now once cli is installed you can create a new nest project by just running nest new dog api which is the name of our application we're going to let this run for a bit answer a couple questions we're gonna use npm for this project and we're all set now just to run our nest app we can go into the directory that it created which is dog api and run npm run start now this is going to fire up our server and we can open up safari back on and go into localhost 3000 which is where our app is running and you can see that it runs when you get an hello world back on the main index route okay so now let's update the code that we have so i'm going to run code dot to open vs code in this directory and let's go from here so what does nestjs installed by default you have a source folder which is where code is going to be and it has entry point which is main.ts where it creates your nest app listening on the port 3000. app is created using the app module which is just a class that is defined here according to the module that next js exports what this module has is imports of other modules if you want to use other modules then it has the controllers for your app and the providers of your app in this case you just have one controller and one service you're going to keep it simple like this the controller is the one responsible for receiving the requests and propagating that request into the correct service in this case it has only one route defined which is the get route and it just returns the app service function get hello returning the string so if you can change this function you can say hello from nest js for example hit save and then in our browser we can just refresh the page and this is the return that we got this can be anything can be an object can be an image anything that you want okay so now to the part of creating our api in five minutes now with the nest cli you have a couple of commands that you can do so if you type nest help it's gonna list all the commands that you can perform with the cli now we've already used new to create our this api we then run start on the npm run start and we have a couple more that we're not going to use for now the one we want to take close attention to is this one this generate command or g for chart the generate command takes a couple of parameters afterwards and in this case what we want to build is a resource now typically a resource refers to a schema of an object that's going to be used in an app so in our app that we're creating our resource is going to be dogs or dog breeds in this case just breeds or it could be users it's another resource and this is the greatest part about the next cli so if i just run nest g for generate resource it's gonna ask me for the name of my resource that it should enter in plural so i'm gonna type in breeds we're gonna be using a rest api a normal rest api and we're going to say this is the important part is asking me if i would like to generate the cred entry points and i'm going to just press enter because the default is yes and this is where all the magic has happened if i now go back to vs code you can see that inside sources i have a new folder called breeds this is our resource it creates a couple of things dtos and entities we're going to cover that later in our next js series tutorials but what we want to actually look at is let me expand this i want to look at this so this has the same structure as the app module most modules going to have this structure it's going to have the module itself which is going to import the controllers and the services that it needs the controller in itself the same structure as before except that our controller decorator has the string breeds as a parameter so now our app has an extra end point and it starts with breeds then automatically i also define our post endpoint our get endpoint our get with an id parameter to put and delete all of the endpoints that we need to make cred happen we got him so let's try this out so now if you go back to our browser this was the main entry point but if we now type in breeds now hit a different controller right because this controller has defined that its entry point is on breeds so it's slash breeds directly but one limitation of the browsers is that on browser windows you can make only get requests so you cannot post or put or delete so we cannot use our other the other http methods to trigger all our functions so for that i use postman so you've probably heard about postman before it's one of the most known uh applications for api development or api testing and it's gonna enable you to make all the other types of requests to your apis so i've already installed it but if you haven't installed it you can just create it you can have an account and then it's gonna take you back to downloads so once you have postman installed you can just fire it up and this is what you're gonna see let's try first to create a request the same request that we are doing on our browser so it's a get request you select get right here and enter http localhost 3000 breeds and we got exactly the same results we got a get request to our api now let's see what other method methods we have right here we have a get with a parameter so it's slash something and then this slash is going to convert it for an id so that you can then use it here extracted from the the request and pass it to the function below for the service so right here if i enter breed slash 2 this is going to be the id it's going to return me this action returns a number to breathe why does it do that because if you go back to the function that is responsible for handling the request all it does is return a string with our id right here now the same thing goes for the put http method the delete method and it's gonna just proxy back to the functions in the service so now for the fun part which is actually using a database to control our modules so nest js makes it really easy by covering it in the documentation so if we go to the technics section and click on this is how you can use mongoose to serve as an orm between your database so i'm going to copy this command go back to the terminal and install it okay so what you can see here the first part is to connect to the database you do that in the module so we're going to copy this line right here and then just import it so now we are connected to our local host at nest database which is a database we don't yet have we're going to create it afterwards so this is going to assume that you already have mongodb installed in your machine but if you don't have you can go to the mongodb website and download okay so this should take care of the connection then we need to define a model that's going to be the object that's going to be saved on mongodb itself we're going to follow the same example i'm going to create a schemas folder in the source directory i can create a breed dot schema.ts we're going to copy this example and change it for what we want to do so pasting that we only need to change the cat document to be a dog document a breed document which is going to be of type read this is a typescript specific but you can also follow other examples on javascript alone so this what this is going to do is to create a schema for mongoose to be able to know how to save the the data into the database so our breed is going to have a name and we can't be all jests for now only a name for now so now our scheme is created what we need next okay so then what we have to do is on we're going to copy this line which is the only thing we are missing on our module of the resource so we go back to the breed dot module and on imports we're going to add this import the mongoose module and we're going to say that it's going to have a module with the name of the breed name let's import breed from our schema and the schema is going to be the breed schema also imported from the file we created now after our model is registered in the scope we need to use the inject model for the service to be able to manipulate the documents of the collection directly so for that we're just gonna also copy this constructor so if you go back to the breeds service this is the guy that's going to need the model injected into it we're going to import that decorator from the mongoose package change for our schema name which is breed and the model also imported from mongoose is going to be modeled after the breed document and now we can just change this name for breed module so that we can use it within the service okay once all of this is done we should be able to create documents in our database now to be able to see the documents in my database and edit them if i need to i use nosql booster i have a lot of databases already but you can see i don't have a nest database so nest in the connection and the mongoose or am i going to take care of that for me once i try to insert my first model so let's try that first if we go back to our bridge service here on the create function this is the function that's going to be requested when we do a post to the breeze endpoint it should look like this where you're going to create a model from the model we us have injected into the constructor which is a document then we're gonna just hit save on that module and someone goes saves documents into the database so first of all we're gonna need to be make this function asynchronous and just for typescript we're going to specify the return of the function that's going to be a promise of of a breed so let's just have to change this what we're going to return is going to be a new instance of the breed module created with the parameter that we are passing to the function is going to be the body of the request and it's gonna hit save on this model so we're now gonna run our nest app with start dev this way whenever you make a change to a file it's going to auto compile and update the app which is going to come in handy later so it's npm run start dev you can see that just a script that it's in the package json of the the project that's gonna run nest with the command start and the watch flag so now this is running we can go back to postman we're gonna make a post request to local 3000 slash breeds let's see where it returns here you can see it created a document already so if you go back to our database and we refresh our localhost we can see we now have a new database in our server and inside the database we have a breeds collection and our object that we just created is just inside of here so let's try and now create an object with a couple of attributes right because we should need a name i'm gonna go to body set it to json and you're gonna pass a name into the request name is going to be beagle for example let's run this the nest api returns our document and if we go back and run again we have two objects now the empty one we created before and a new one with the name beagle now that everything's set up the rest of the things should be easy to implement when we return find all we also have to make this a sync because it's now connected to so now to return since we have the connection to the model we can just go this dot breed module find and hit save now this find all function is being called once we hit with the get on the route it's going to call the breedservice.find all so let's on postman let's hit get on breathes you can see that returns an array of the objects that we have inside it okay now let's try and find a specific breed for now our get with the slash id returns and a string with the number that we passed into it let's make a change that we pass a name in and it's gonna return it's gonna return the breed of that specific name so this is gonna start getting a name which is of type string what it's going to do is go to the model and find one where the name is the name that we passed so now under control we just have to change what it passes to the controller because we're not going to have this anymore so this is going to be name instead of id just to keep things organized so now we should also change this all to name we're going to remove this plus because we don't want to convert our string into a number and if we go back and run here one it should no longer return anything it's empty but if we pass in beagle we have the document that we created where the name matches our query parameter now let's try put but is used for update normally so let's do the same thing let's change this to receive the name remove here and on the update function change the id for also a name which is a string and which should return this.readmodule update1 where the name is the name we passed and then we're going to use a specific things to update where we're going to set the update breed dto object so everything that's going to come on in the body we're going to update on our module with this specific name so let's try that one let's create a new breed for example so i'm going to make a post with a name of labrador for example so we now have a new document also we can retrieve it labrador and we can try and update it so if we run a put method to our breeds labrador and we change the body to have something else for example fur type and you can say long just an example here and if we send this you can see that no change was made and this is because if you go back to our breed schema you can see that our breed only expects to have a name the the id and the underscore v are all provided by mongol so they don't have to explicitly be declared but it only is expecting a name on the document so for anything else to be able to be persisted to our module we need to create it here let's create a for type that's going to be also a string if we go back to postman again and try to make the same request you can see that now we have a warning that one was modified so we found one to match our query try to modify one and we got the ok so now if you get the same search back you can see that our document has a new attribute called fur type the same thing here on the database right we have now name and fur type so all we need now is to be able to delete it so be able to use the delete http method to delete our document so we go back to the breeds controller we change also the same same thing here we're using names just to simplify things but you should also be using should always be using the ids of stuff we're going to delete all of this change it to name and on the last one just remove the cast 2 integer on the server is gonna do the same thing name is the type string and we're gonna use the breed module to delete one matching our name let's just add a sync to all of this which is the best practice and go back to post button we now run delete with the same query here the body is not necessary just you can send none and if we run this request you can see the same results deleted one document that matched our query so if we go back here we are back to two documents the empty one and the beagle one you could do a lot more with nest js for and if you go to the documentation they have it's extremely well specified but i'm also gonna go through another couple of topics on the channel uh further videos down the line but for example you can handle validation of the inputs that you're passing to the requests if you want our request of creating a new breed to have a specific schema so it has to have all of these parameters they are required and they are the correct type you can enforce all of that easily within sjs also things for caching for logging errors into a specific file or another service file upload sessions management you can serve also raw html or computer html through templates engines sjs is an incredible incredibly powerful tool for server-side node.js applications and it's my favorite by far so if you want to explore more of nest js please go to the documentation everything it's extremely well explained here with a lot of examples techniques and suggestions if you want to follow the channel for more videos on this later we're going to create bigger apps we're going to create apps using microservices to communicate between services and implement validations we can implement authentication of users creation of users using google auth everything else so if you are interested in that please stay tuned for the next videos also like the video down below because it's going to help me out a lot in the youtube algorithm and if you have any questions regarding any of this or any other issues that you may encounter doing more advanced stuff with an sjs please leave a comment down below or also catch me up on twitter i'll be more than glad to try and help you so until the next video i can only wish you happy coding
Info
Channel: Igor Silveira
Views: 13,484
Rating: undefined out of 5
Keywords: crud api nodejs mongodb, rest api, restful api, express api, nodejs express, node api tutorial, dev ed, javascript project, rest api tutorial, express js, mongodb rest api, mongodb, node, node.js, node js, express, expressjs, express.js, api, restful, backend, javascript, express tutorial, express.js tutorial, restful api tutorial, express rest api, server side, server-side javascript, web development, nestjs mongodb, express api mongodb, express api typescript, learn to code
Id: -_TNGrtLeOM
Channel Id: undefined
Length: 23min 57sec (1437 seconds)
Published: Tue Jan 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.