MongoDB Full Tutorial w/ Node.js, Express, & Mongoose

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to our Bongo DB tutorial what we're going to build in this tutorial is a very simple another expression deployed on turbo using the database of course and it's going to have two models it's going to have a profile and a team so that's going to simulate sort of like a like a project for like a team like there's some sort of sport or recreational league something like that we're going to use a REST API to interface with the data so we're going to set up a basic REST API for all the query and sorting data and things of that sort we're obviously going to focus on the MongoDB in terms of topics we're going to use the Mongoose ORM which is definitely the most popular ORM for the JavaScript community for MongoDB and we're going to cover all the crud operations for using and mongoose so crud is create read update and delete and we will cover all four of those in this tutorial again using the REST API this is a beginner tutorial but it's not for complete beginners you should have a basic not working knowledge of HTML CSS and JavaScript as well as how to set up a node express project the the basics of node Express should be familiar to you you don't have to be an expert again this is a beginner project but you should know how to set up a node Express project install NPM modules etc know how to use the static directory as well as templating engines and things like that you will need a turbo account so that we can deploy our projects that is free and your we're also going to use the M lab service for our hosting so you'll need an account on M lab which is also free and you can sign up at M lab comm so make sure you have all that ready to go and then we can go ahead and dive in so in this video we're going to get our tools set up so first thing you want to be sure about is you want to be sure that you have node and NPM installed on your machine so head over to know G org if you don't and make you install the VLTs version right here and you should be all set to go with node and NPM if you want to if you want to check beforehand you can do node - fee and you can see I'm running 8.11 and then you can do mkm - tree to see what version of NPM you are running if neither of these return values for you just go ahead and install the node runtime on your computer and you should be good to go next we're going to need to install itself which I'm going to use a homebrew to do that so brew Sh head over to here and install homebrew if you don't already have it you can just copy and paste this into your terminal and you should have that will install homebrew homebrew is a package manager for your machine it installs well it installs then updates packages so that's what it does and we're going to use that for installing so if you do not have monkey well let's check if you have so one way you can do that is by doing - - version and here I'm running 4.0.1 so if you do not get a return value from this command that means you need to install monka so one way you can do that is brew brew install DB like so and that will install the database on your local machine that normally takes it takes a couple of minutes so just be patient with that and follow the commands whenever you get prompted with further instructions next we will need the turbo CLI so make sure you have the turbo CLI installed you can check by running turbo version and make sure you have a version number like this or higher so if you have a previous version than this that means you need to update and that's very easy we used to do sudo NPM I - G and then turbo CLI and this will install the turbo CLI on your machine and then I'll give you the ability to deploy your projects onto the turbo staging environment which is also free so make sure you have that set to go and once you have all that we should be all set so we should be ready to start with our project and let's go ahead and get started with our project so first things first you got to make sure you have a an account on turbo 360 Co so head over here so that we can go ahead and set up our account so that we can deploy to our staging server this is free so don't worry about that so once you have that open up your terminal and CD change directory to your desktop like so or wherever you prefer to do your work I'm going to do it in the desktop and let's create a new turbo project let's call it proj and this creates another Express project a very basic note Express project so I'm going to open this up in the text editor I'm using sublime and here you will see the app j/s where the project is set up and we have our standard you know our routes our views in our public directory the views are for your templates we're using our the mustache templating engine routes we have two routes we have an API route and an index route these are just scaffolds it by the the scaffold right out-of-the-box we can change these as needed obviously and public is for your static assets JavaScript images and CSS so that is all set to go now if you look at the well let's head over to our terminal and CD into the proj now given that this is a node Express project we have to install our dependencies as defined in the package.json these are not yet installed so make sure you head over to your root directory and then do NPM install in order to install those packages and that usually takes about a minute or so so while that's going let's head over to our app j/s where our project is basically set up and let's step through this to figure out our configuration so if you look at line four you will see that this is where the app is initialized and this is an express app it's called vertex here because that's the vertex Izzie is an Express application basically configured modified for the turbo environment so it's just an express app with a few minor modifications so here is the instantiation but if you look down here on line 24 you'll see another instantiation which takes a config object which is defined on line 11 and inside this config object is where we set up our some configuration options view static directory and most importantly DB on line 14 so what we want to do is we want to use this instantiation instead so let's get rid of line for just remove it and then uncomment this right here and like so actually we can just get rid of this whole thing so now we're going to use the config object to configure our project and the most important line right now is this one right here line 8 where we define our database URL so we're going to comment that out and replace it with our own database URL which for now will be an empty string so what this is going to be is a reference to our local server so what we want to do is DB colon slash slash local host slash proj and this last term right here will be the name of our database so this is the pattern for the default pattern for local URLs so and again the last one here is the name of our database which we can name it whatever we want so here is how we configure our project to run with a local server so what we want to do now is test that so we can do turbo dev server and we will see this message here DB connection failed which is this message right here the on error callback well that's because we're not running a local database so we want to stop the web server and then do command T to open another tab and then we want to do D like that and this will run the local server and all these lines will pop up but most importantly is this last line right here waiting for connections on port two seven zero one seven this is the default port number for local instances so now we're running a server locally on our machine we can head back to our web server and run the dev server again but before we do I'm gonna include an on success callback so that we can get a confirmation message DB connected in order to confirm that the database was successfully connected to our web project so let's go ahead and check that out so we can do turbo dev server again and there we go the database had is successfully connecting and our project is running locally on localhost 3000 so we can head over to localhost 3000 in our browser and we can see our project running locally this is the how your project should look while running the database so this is now database connected to your local instance so everything is ready to go our models for our project to work with which will be profile and team and that's it so let's go ahead and get started let's go ahead and head back to our terminal and run the server so in a separate tab I'm running the local server and then in the web server I'm gonna run trip out dev server and then head over to localhost 3000 to make sure everything still works which it does so everything is still in working order so I'm going to turn off the web server make sure you're in the root directory and we're gonna create a new folder called models which is where we're going to store our models models for profile and team which will define the schemas for each so we want to head over to that directory and create a profile J s and we may as well do the team one right now as well and then head back to the root and let's go back to our models directory and open up the profile J s and here is where we will define the schema the attributes which comprise a profile in our project within the context of our project so we're going to need the mongoose ORM so let's go ahead and import that and then let's go ahead and create the profile schema which is a new mongoose schema object now make sure you insert the JSON argument here and then let's go ahead and export it module exports and this is a mongoose model which we will call profile which takes the profile schema that we're about to define so in here is where all of the action takes place here is where we define the actual attributes which comprises a profile so first name last name email password things like that all that goes in here so let's go ahead and get that process started so we want to start with the first name and these all take JSON arguments or these are all JSON values excuse me last name age team and position okay great so these are all empty JSON values but obviously they shouldn't stay empty so these all of these attributes are going to be strings except for age age is going to be a number so we want to define that in these JSON arguments we inside these JSON values we define we determine the datatype of the respective attribute so all of these are going to be string the except for the age which is going to be a number and then technically we can stop here and this is a complete schema but we can actually go we want to take advantage of a few more options we want to assign default values to all of these and in the case of all the strings the default value will be empty string in the case of the number it will be zero so the default value basically gives these attributes an automatic value if the user doesn't input one during the process of creating the profile so when there's data being sent to our our server if the first name attribute is undefined the Mongoose schema will insert an empty string on our behalf which is a nice tool so so this is one extra tool we can use that provided to us by Mongoose to make this our data more consistent in the database so another value another tool we want to use is called trim and this is a boolean which we will set to true so what this does is that it removes any trailing whitespace so for example if we have a user named Bob like so Bob during registration Bob may have done something like this where he put an empty space and at the trailing edge by mistake in all likelihood this is not on purpose so we want to trim those trailing and as well as preceding white spaces so that this doesn't mess up our database integrity so we definitely want to take advantage of things like that so we want to trim the last name as well team and the position and there are a series of other options we can include which we won't get to for now just just understand that the Mongoose ORM provides us a series of tools like this which makes the data more consistent within our database so that it sits across all of our records there's more consistency within the attributes which is very very very very useful so now that we have our profile setup schema set up the question is how can we query those profiles how can we use this to to fetch the profiles from our back-end so what we're going to do is we're going to use one of the provided from the scaffold specifically the API wrap the API route is provided to us automatically from the scaffold we're not going to use what's in here so let's get rid of this and want to create our own routes instead so what we want to do is create a get handler which takes a string argument and we want to call it profile and this get handler will fetch all the profiles currently in our database so this takes a wreck request and a response object and for now we're just going to return a JSON response with a hard-coded output sometimes these are called end points and Stan's will just call this end point so right now that's all it's going to return right so what we want to do is we want to test that end point by heading back to our terminal running the dev server head over to localhost 3000 now if you look at the apt yes you'll see that the routes are connected on the bottom and you'll see that the API route is connected in the path with the path slash API so if we do slash API and then slash profile that will invoke this endpoint so we do slash API slash profile and here we have the endpoint we just wrote a few minutes ago so that worked so now what that means is within this endpoint we can query the profiles using this schema so let's go ahead and do that so we do can't we have to import that of course okay so now here we have our profile model which is a mongoose object so we want to run the find query which returns a promise and the promise success block returns the profiles from the database so we can get rid of this now and this right here is our first slash Mongoose query this is going to query every profile currently in our database our back-end and return them in this success block right here so we can do rest JSON and then confirmation success you know profiles and that will return the profiles you know or browser just like it did over here and before we finish that there let's handle the error scenario so this is the catch block which is the error case so we want to return an error message here obviously the confirmation is not successes fail and then we should return a message from the error object which should indicate what went wrong so this query right here is for every profile in our database for database so now if we rerun this this request we should see an empty array because there are no profiles in our database so that's that's the expected outcome because right now we don't have any profiles so here what we've done is we've set up a very simple query for schema that currently is defined in the models as per this set of attributes right here and then we created we ran a request against that schema but we don't have any data in the backend so right now we're just getting empty result set so so far so good but obviously we want to have some data to work with next one is setup database with some initial data what's often called seed data using some static JSON objects and that we will insert those records into our database so that when we run this query we have some stuff to work with and my terminal is right here I'm going to turn off everything that's running so we can start from scratch so first things first let's run the manga server locally so by doing d and then head over to your web server and the turbo dev server and then make sure that everything still works so here is the API slash profile route that we created specifically to fetch profiles and again there are no profiles so let's go ahead and turn off our web server and let's create a JSON file which will we can use to insert some initial data into our database so right now we're doing what's called we're using what's called CD David we're going to speed the database with some initial data so that we have some stuff to work with right away is a JSON based document storage database so what that means is if we just create some JSON records JSON objects we can insert them directly into our database using the CLI which is exactly what we're going to do so first things first we've got to create the JSON files by the JSON object so let's create a directory for this let's call it initial for initial data let's CD into the initial folder and let's create a profile JSON file head back to your root directory and then actually no you want let's stay in the initial ok and then open this up and let's create our profiles so this this set of profiles we're about to create should be consistent with the profile schema that we defined in the previous video so first-name lastname age team position so we have first name last lasting age position and ting I believe we have team on there yes notice how all these are string values except for the age because that that is defined as a number in the schema so we have to be consistent with that over here so now that we have our first profile we can just add a few more all right and let's see actually I'm going to add one more okay so here I have four profiles to start with all JSON objects fitting the schema as defined in our models directory so we can insert these records into our database right away so that we have some data to work with so let's go ahead and do that so the way we want to do that is through the the shell so we can directly the CLI I should say we can directly interface with our database using the CLI so one way we can do that is by doing like this just directly connect to our database make sure your instance is running otherwise this won't work and I'm gonna show DBS right and we can see what our current with what the current databases are in our database so we're gonna create a new database let's do ctrl C and we're going to insert these records into that database as a collection so a collection is a basically it's what it sounds like it's a collection of records all under one schema so what we want to do is mom we're gonna use a tool called import and it takes a few arguments the first one is DB and that's going to be the name of the database if you recall we set the name in the app J s called proj so we want to say DB is proj so that we're going to interface with the same database and then collection it's going to be called profiles it was just basically the pluralized version of our schema the profile schema profiles is plural and then we can we can pass in a file argument and that's going to be the JSON file profiles JSON so just so you understand what's going on here the Mangal import is going to create this database prash because right now it doesn't exist and then afterwards it's going to create a profiles collection which will use the profiles JSON file for the initial set of data so once I press enter here is that imported for documents which are these four documents right here so it created those four records in our database so we can head back to our root directory and run turbo dev server and now we can test this endpoint again and now we have our four full poplars for quarterbacks where three quarterbacks and one wide receiver so it worked everything worked one thing that's very worth pointing out is that there's this extra field called underscore ID which we did not define in here you will not see an underscore ID in these initial records set that's because assigns that for us automatically does that on our behalf and these are unique identifiers for each record in the database so this is a unique number that ties to this entry in particular it's kind of like a social security number it only it only relates to this one record and does that on our behalf so now that we have some data to work with we can start running queries in our API route let's go ahead and find that right here in our API route for specific profiles based on things like you know position position team things like that or start running those kinds of queries basically adding filters to our query so we can get specific profiles based on parameters that we with the project may need at a certain point in time at this juncture of the video a good exercise would be to do the same thing for teams you may remember you may recall we created a team's model which is empty so we want to create a similar set up so that would be a good product good assignment to work on the team should be the attributes should be something like team name City conference so this is American football we're talking about so you know team like the New England Patriots is the the the city is Boston the name is Patriots the conference is AFC American Football Conference and that should be enough for the team schema so so yeah that's it let's try to get that put together here in the terminal to run the manga local server and the web server okay and then if I run a query for all the profiles we see everything that we added to our database so now what we want to do is query the same data with specific filters so that is done inside here the API route inside this this find method from Mongoose inside here we can add a JSON object that specifies the filters for example if I say I only want to query for profiles whose position is QB I would do it like that and then if I rerun the query everyone but Odell Beckham's should be returned see his position is not QB so here we have three players all of whom are cubies and then we can do the same thing for a wide receiver and now we get only Odell Beckham who is of course a wide receiver so the filtering of your queries and Mongoose is pretty straightforward we want to make it more dynamic of course by having the filter coming from the actual user so what we want is something like this to return only the cubies so right here this is the request query we can parse that out inside the API route like so so that this req object gives us the query which is really this key value pair in JSON form so it's ready in JSON form for us which is nice so now we can just insert the query object into the the fine method from mangu so if I do this now I'll give us all the cubies if I do wide receiver it gives us only the wide receiver we have in our database which is one player Odell Beckham if I want to query by team I can do team like that and here I have the two players you know on the Giants of course I can do the other teams as well whoops so here is the one player on the Patriots and if I query team that's not that doesn't have any players in our database of course we get an empty array which is what we expect so that's it it's good the query filters work so far we can also query by the numerical value so here we have three players for players excuse me ages ranging from 24 to 41 so let's say we want to query for profiles who are only older than 41 or we can do exactly 41 like so so this gives us the one player who's 41 but if I do 40 then I get nobody so maybe what I want to do instead is older than 40 right so the way you would do that is inside here the way would look is you query by age and then you pass in another JSON object and then inside here you have a special Mongoose key with the dollar sign that's denoted by this dollar sign that means it's a special Mongoose key and the GT stands for greater than and then you can do 40 right so here now we should only get Tom Brady who is older than 40 and if I do 30 then I get three players Aaron Rodgers Eli Manning and Tom Brady and then I can also add in a less than filter so query dollar sign LT for less than and then 40 this will give us the profiles ages between 30 and 40 and so that now we should only get these two players and that gives us Aaron Rodgers and Eli Manning and so that works and so it's up to you how you want to structure this from the actual query itself the query a request query itself but for now I'm just going to use the the greater than exclusively so one way we can do that is if we see the age parameter at all if so what we're going to do is we're going to create a filters object and we are going to see here if the query contains the age key so if this age key is is present inside the request query what we want to do is take the filters and set the age as greater than the query age value and let's see here the best way to do this would be let's set the filters to the query to begin with like that and then we can pass in the filters like so so by default if the query the request query has the H key we're querying for every profile older than the specified value so right here line 12 we want to wreck doc query excuse me ting okay and that should take care of that so now we get Tom Brady here because he's the only player older than 40 if I enter 30 I get everyone older than 30 so forth and so on if I enter 20 I get everybody so here I'm just adding a default greater than if there's an age key passed in that's only 13 inch capacity and if there's no H key passed in the filters will be automatically inserted inserted into the request basically as is so I can do team and giants and we still get these two or we can do position and QB and we only get the cubies we can do wide receiver so forth and so on we're going to query for a specific record so that we don't have to filter add filters based on an attribute every single time we can query for a specific entry based on the unique identifier so let's go ahead and get that started now I'm going to run the local server and then the web server and then let's go ahead and set up another end point for querying a specific entity a specific profile I should say so let's go ahead and set up a route or route for that it's going to be another get and the path is going to also be profile but this time I'm going to add a request parameter called ID and that's going to be a variable passed into the actual URL and then the callback for now let's just have it hard-coded and this ID program can be parsed out as a program like that and then we can just return that in the JSON response for now just to make sure everything is properly set up so let's test the endpoint all we have to do here is do another slash and then some random text and here you'll see that the data is returned to us pretty much as is which is what we're specifying right here good so it's connected so if you look at the profiles you'll see that they all have an ID string that's randomly generated by and assigned to the entity by so we can query specifically by using that ID so what we want to do is grab the profile and this time it's find by ID we passing the ID and that returns a promise again same as before and here is the success callback so we can do confirmation success here and in the air recall that we want to handle the error appropriately by returning a failure confirmation with the error message so now what we can do is we can grab so make sure you have everything here like this we can grab the profile ID like so and in this case we have Tom Brady and just append that to this route and now we get specifically the request results for Tom Brady and of course we can test all the profiles that way so we do Aaron Rodgers so forth and so on we can confirm that they all work and then what we want to do is make sure that it works in the failure scenario as well so for example if I do if I enter an ID that doesn't exist it should return an error message now this error message is a little bit hard to decipher if you're not not a programmer or not very familiar with sort of the Mongoose error styles so instead of returning just the error message we should replace that with profile ID not found a much more human readable message so that it's very quick and easy to see what exactly what went wrong so I think that would be a better way to handle that so that when you when you come across this error it's immediately obvious what what went wrong I was just testing something there don't worry about that so that it's a lot faster to determine what the proper adjustments are and that's it and this is one which is a way to query a specific record by the identifier which is a much more efficient type of query than using this this kind you don't want to use this general query every single time because it's not the most efficient if you can query by a specific key and ID that's much faster so you want to do this one whenever it's possible or whatever it's appropriate you want to use the identifier to query for a the cracker we're gonna create the ability to add records from the web interface rather than from the client-side CLI excuse me so that users can add profiles when they sign up so that's it let's go ahead and get started so now what we want to do is add the ability to create a profile from the web web interface so what we want to do is go to the API or route where we set up our queries and set up another endpoint where a user can create a profile probably through signing up this all this usually happens through a post request rather than a get request so these this is a get request that's a get request but this time we want to set up a post request because the adding data is usually happens from a post request especially doing one dealing with a REST API which is essentially what we're setting up here on a basic level so here we want to set up a post and point and then like usual we just want to return a hard-coded confirmation now the data in a post request is in a node Express application is returned to us in the req body the body attribute of the request so when the post data is submitted to the endpoint here is where the actual data can be retrieved so now the question is how do we set up the post request well that normally happens through a form on the on a web on a website in actual HTML web page so if we go to the home page of this project localhost 3000 here you will see our home page and this is just regular HTML CSS JavaScript etc and this page in particular is inside the fuse directory right here index dot mustache and mustache is the templating engine that is installed by default so we can use this to create a form where a new profile can be submitted so let's get rid of all these other all this other content because we don't need it anymore so let's get rid of all this stuff and here inside the last remaining give let's set up a forum where we can create inputs for each of the attributes of the profile so we have first name oops this should be the type is text excuse me text text inputs so we have first name last name team position and age now these attributes these name attributes should correlate to the properties in the actual schema so they should match up with what we see here in also in terms of casing upper case lower case said that all has to match up so make sure yours matches up as well and if we take a look at the home page now we should see this it's gonna be hard to know what field corresponds to what so we can use the placeholder attribute for that first name last name team position age now we have the placeholders makes it easier to remember what goes with what and the final input should be a submit type doesn't need a name but it could use a value add profile so now we have a button which will send the request now now we have a form here that right now points to nothing so we want to point the data of this form to this endpoint so the way you do that is by adding two attributes in the form itself action and method now the method is post and that this post right here is in relation to that post right there in other words this is a post request and the action is slash API slash profile as specified by this path right here and it's slash API because it's that's the original path right there so slash API slash profile is where this should go this data should be submitted to and if everything is properly set up this is the response we should get basically just it'll just spit the data right back to us in JSON form so if I load the homepage and I add another profile I think it's one word here we have the data basically just returned right back to us in JSON form thereby confirming that it worked at this endpoint this endpoint right here is successfully receiving the data so now that we've confirmed that we can now create an entry a profile entry in the database using the create command and we can simply take the request body which is the data in JSON form it's all of this already in JSON form and run the standard promise sequence now Mongoose returns a profile or the object the document that's created it returns it back to us in the completion block the success block so right here we can just return the success confirmation with the profile that was just created and then in here is the error block so we do what we normally do here we turn a fail message a failure confirmation with the error message so that we can see what went wrong and then we can now get rid of this and if we go back to the home page we can try it again QV now it's going to return the json Agamben notice this time there's a version an ID and a version that comes from so what that means is the requests are successful if I actually take the ID and run the ID request we get Russell Wilson again and if I run the general profile request we get all the quarterback all the players including Russell Wilson the player would just create it who is a quarterback so if we do position QB now we get Russell Wilson as well inside the results set and so forth and so on so so we worked so this is the the proper way to handle inserting data into the database which almost always happens through some sort of form of this sort like like this is a very conventional way of submitting data from a form to a post handler like that and then and then inserting that data into the database this is the proper way of handling that situation so hopefully you got that working at this juncture a good exercise is to continue this process for the teams you may have noticed that we haven't really been doing much work with the teams because this is something I want you to do on your own as you go through this project so you should set up corresponding endpoints for profile and teams and as well as post handler so that you can create a team through a form on the on the home page in this fashion simple way to update the data it'll be done through a simple get request which is not the conventional way by the way we're going to take a little bit of a shortcut here just to illustrate the concept as well as the the commands to create an update and then we'll update some of our profiles and and that's it so let's get started and so let's say we want to update this right what I'm going to do is set up a an endpoint just for updating so it's going to be right here router this is going to be a get but normally this is a put the reason I'm using a get is just to make this process a little bit more convenient but normally this would be done through a put its a profile then that update actually this should be over here you may be wondering why I placed the handler above this one because this one is a generic as a generic ID parameter after the profile path which will be interpreted first and if I put this one beneath it it no request will ever actually get to this endpoint because this one will reach first if that makes any sense however by putting this one above the update command will happen will be interpreted before this one and so we can we can process the requests so let's try sending a hard-coded hard-coded response and let's see if that works there we go and if I go back here this still works fine so we are set to go okay so what we want is the query parameters then this should require ID and key value pairs for what to update so for example it might be like here's an ID number for Russell Wilson so the request would look like this ID equals that so we're specifying which profile specifically we want to update and then let's say we want to update the team let's say he got trade it's a team equals Cardinals and this will update the profile this particular profile the team value and that's it or maybe he you know he aged one more he got one year older or he changed position etc so what we want to do is grab the ID and then we want to get the profile and then find by ID and update and this will take the profile ID argument and then the query and then new equals true this last part is a little tricky what's happening here is that by default Mongoose will return the the record prior to the update or in reality we normally want the record after the update so by returning by passing in this true boolean that's what we get it's a bit of a sneaky gotcha that you want to keep in mind about Mongoose and then here we just do what we normally do let's get rid of that and the error is the same as always just return the failure confirmation with a message and the success return the updated profile so here we are grabbing the profile ID from the query and then we are identifying the specific profile based on that whatever else is in the query parameters we pass in here as the updates actually I'm going to do one more thing just to be sure I'm going to remove the ID so now all that's left are the parameters that we want to update like the team the position the age things like that so and then we return the new version over here so let's try it so now when I run this request it should say team C Cardinals and there it is now if I run the overall request head down to Russell Wilson it says Cardinals let's say Eli Manning let's insert his ID while city age is 38 so at some point I'll turn 38 and there it is and then if I go back here you'll see that the age is still 37 if I reload it now should say 38 so this is a standard update using and Mongoose again I want to point out that this is normally handled through a put request right here put rather than I get but the reason I set it up as a get it so that I can run it through the browser like this for a convenient way of doing that rather than sending up a whole web front-end just for this however just be aware that this is not this area right here is non restful very important rest full and normally it should be handled through a report so this is how you handle updates in and Mongoose I recommend you set up the same thing for teams now so that you can update your teams if I'm not really sure what what categories are the team will change sometimes cities teams change cities fairly frequently so maybe that's something you might want to test and that's it with the sequence the crowd sequence by deleting a few records and making sure that that can be handled as well like before we're going to set that up through a gap request which normally wouldn't be the case but for the sake of convenience I'm going to set it up as they get requests so we can we can test it run it through the browser and make sure everything works so let's go ahead and get started here we set up this request right here before updating I'm going to do one more after it as another get a profile and this is gonna be remove to remove a record a specific record and it's gonna be the same idea it's gonna take an ID and in this case that's all it's gonna need because that's enough to identify which record we want to remove right so we want to grab the query object and then we want to do profile find by ID and remove that's the Mongoose corresponding Mongoose query for removing a profile and then this is going to return the usual this is just a promise but this time there is no profile keep in mind because there what excuse me the profile has been removed so what we want to do is handle the error like I normally do and then here on the success return a success confirmation and then just return a message saying profile query the ID successfully removed that's good enough for now and that will confirm that the removal of this specific record is complete and successful so let's go ahead and test it out so it's profile slash remove and then we have to pass in the ID into the query so let's say we want to remove Aaron Rodgers so we do slash profile and then don't forget the endpoint is remove so slash remove and then we pass in an ID filter and then we paste in the ID and then profile was successfully removed so if I do a general profile request now we should no longer see Aaron Rodgers and that is that has been completed so obviously we can continue testing but oftentimes what happens during your throughout your testing process especially locally is that you end up with all these records that were just inserted for pure testing purposes and have all sorts of inconsistent data patterns and things like that like maybe you initially had the age of string and then change your mind later making it a number so forth and so on things like that this is very common in a local testing environment so it's not unusual at all for it within local testing to want to remove all of the records the whole thing the entire the entire collection would be a way to rephrase that so this happens a lot so what what you want to do here instead of removing everything one at a time because maybe you have instead of four or five you have 50 or 60 so that can be very tedious to remove everything one at a time what you'd rather do everything why you rather do instead is to remove the entire collection in one command and we can do that through the CLI I do this a lot through the CLI so if I open a new tab I can connect to the database directly and the name of the database if you ever forget you just go back to the app chest and you just look it up right here in the URL and I can just connect it directly to the database and so here I am and then I want to do show collections to see what I have and currently have I have profiles and then I can do DB profiles and then find and then I can see spell the wrong profiles I can see what profiles I currently have in the backend the database which is obviously the examples we used in the video so far so I can just draw the entire collection very easily by doing instead of fine I can do drop like that and they should return true if it was successful so now if I go back to the API and I run this request I get an empty array because now we removed all the profiles in one quick command so that's another way you can do that by interfacing directly with the CLI rather than Mongoose and then we can when we're done with them just to exit we're done with that and then now we're back down to zero so that's it that's another way of quickly removing a whole set of collections which again is very common in a local testing environment because oftentimes you have all these records that we're only there for testing if the data is all messed up and things are inconsistent and you just need to sort of wipe your slate clean and start fresh which is what we just did right here so that's it that completes our crud operations for now there's obviously a lot more that you can you can look into using the slash mongoose documentation I highly recommend you look into the documentation for mongoose Alissa's damn p.m. page what we really want is the documentation page and it'll give you the entire set of api's that you can use in the mongoose ORM which extends much further than what what i've shared so far but in this series so far we've gone through the basics which is enough to get you started and putting together a very basic application web application ploy to a staging environment and get our database working on an actual database server so we are going to get that set up today and that's it so let's get started you are going to need an account on M lab right here so make sure you have that as well as turbo you should already have that but if you don't go to turbo 360 Co this is where we're going to deploy our projects and we're going to host our application on here and host our database on here so make sure you have that properly make those make sure you have those accounts properly ready to go so what we want to do next is head over to our project and we're going to make a slight adjustment here so this early on we had commented out this line right here which is using environment variables to establish the database URLs so this one right here MongoDB URI is your local environment variable for the database local database so really what we want to do is we want to reuse this right here so if we head over to the env file right here is where you will see the environment variables configured for your project so we need to define the MongoDB URI and that is going to be our local URL what we've been using so far so now if we head over back to App j/s instead of using the actual string we want to use the environment variable like so and this is a better way to handle it so what we can do now is test it by running the server and then running the dev server to make sure everything still works as expected and it does so everything is still set to go we can just run it one quick query to make sure about that and just confirm that everything is still working which it is that's great so we're good to go on that so now what we want to do next is set the production you will database URL and this is the M lab URL so we need to establish that first so we head over to M lab and we sign up if you don't have an account I already do so I'm going to login and we now want to create a new database right here so make sure you click on that you can choose any of these three I want to use Amazon because that's my preferred provider I'm going to we want to create the sandbox account because it's free I'm gonna use a u.s. used one it doesn't really matter but I'm in the East Coast so I'm going to use US East one database name so Farraj it's good enough turbo approach doesn't really matter but this will help me keep track great and here are some just configuration options etc and then we go ahead and create the database and this is going to create the database for you right here and we can click on that now and we need to create a database user which we can just call admin for now so we the user without we create needs a username and a password so we add a database user will call it admin and password will just say is turbo 360 obviously you can make these wherever you want and in doing so we now have our production URL string right here so you copy that and then you head back over to your project and then you enter you paste that in but make sure you have your user and your password so the user well the password is turbo 360 and the user is admin and so now we have our production database URL right here and that's ready to go so now we can head back to our app j/s then really we can just uncomment the original URL line and remove this and so what this establishes is that if the environment is the dev environment or the local environment it will use the local database URL otherwise it will use the production database URL so it's important to understand here is that the turbo environment is right now dev inside the env variables env file but when you deploy the project to your turbo staging server it will automatically switch to production so you don't have to change this in fact you know you really never should change this so now what we need to do is set it up so that we can deploy our project to turbo so we have our M lab configuration all set that's done we're ready to go with that so now what you want to do is head over to turbo and sign up over here which is free or you can sign up on the right side if you don't have if you don't see this and then log into your account and then in your projects you want to create a new project here called project or demo whatever you don't need a description though just go ahead and create it and click the Create site I'm not going to do that because I already have a project set up for this and when you do that you should see this interface and what we need right now is the app ID this is what we use to connect our local project to our staging server on turbo so you head back to your terminal you turn off the local server and the first thing you need to do is log in to turbo like so and just log in using the account that you use to set up just now and then you want to do turbo app and then you paste in your app ID from here just copy and paste it right there like that and this command will connect your local project to your staging environment on turbo it's really that simple and then once that's connected you're all set to go you do turbo deploy and they will deploy the project to your staging environment on turbo which usually takes around a minute and when it's done it will give you a staging URL you know a web-based URL that's a live web URL that you can hit on your browser and check out your project so mine is wrapping up just now and when it's done right here you get that deploy complete message and this is your staging URL right here then that is where your project is hosted that huge copy and paste that into your browser you should get a you should get the interface that we had last time locally but now it's on our browser so before we test anything let's copy that over into another tab and do API profile and see if we get any kind of response which we do and that's because it is currently connected to our M lab account right here and if we click on the home we will see that we have our turbo progr I here of course it's empty there's nothing in here right so what we can do next is head back to our home page and add our first record in our production database or at least our staging database so let's see here whoever not gotten to yet Matt Ryan Falcons quarterback 32 so let's see what happens here so here on production we get the JSON values for the entry we just added with the entry so that's a good ID excuse me so if we head over to the EM lab page you will see if we reload the EM lab you will see the profiles has one document and that corresponds to the entry I just inserted and more importantly if we head over to our API slash profile page sorry that's localhost if we head over to our API slash profile endpoint we now see matt ryan the quarterback who we just entered into our production database we can now grab the ID and then do a back slash ID and we get the same person it's only one anyway we can test all the filters so position equals quarterback and we still get that Ryan because that's the only one if we try a wide receiver we get empty array so that's good we can do profile update ID perhaps I got the age wrong I don't really know his age so I'm just guessing so maybe it's and then age maybe he's 31 and then 31 and there we go and everything we set up before now currently works on our staging environment just like we saw on local so everything is successful on staging as on local which obviously is very very important and and that's it so if you got all this working congratulations you have a nerd Express application with a M database connected and successfully reading and writing data to your database so that's clearly a big step towards your development as a full stack engineer and hopefully you got everything working if you have any questions comments anything like that feel free to shoot me an email you can reach me at the Kuan at turbo 360 CO that's my email and I'll get back to you soon as I can and and yeah that's it thanks again for watching and best of luck in your future endeavors
Info
Channel: freeCodeCamp.org
Views: 130,383
Rating: undefined out of 5
Keywords: mongodb, mondodb tutorial, mongodb course, mongodb tutorial for beginners, RESTful, REST, REST JSON, RESTful api, express api, http requests, nodejs json api, nodejs express, mongoose, express, turbo360, learn mongodb, mongo
Id: 4yqu8YF29cU
Channel Id: undefined
Length: 75min 17sec (4517 seconds)
Published: Thu Sep 13 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.