MongooseJS Essentials - Learn MongoDB for Node.js | Patrick Schroeder | Skillshare

MongooseJS Essentials - Learn MongoDB for Node.js

Patrick Schroeder, Teaching JavaScript Courses

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
7 Lessons (42m)
    • 1. Project Overview

      1:05
    • 2. Understanding Mongoose

      2:43
    • 3. Mongoose Schema

      5:45
    • 4. CRUD App Part 1

      13:41
    • 5. CRUD App Part 2

      3:30
    • 6. CRUD App Part 3

      8:05
    • 7. CRUD App Part 4

      7:29

About This Class

Download completed course files here 

In this course we will build a simple application to show how to perform full CRUD (create, read, update, delete) operations within Node.js.

We'll be using the Node module MongooseJS. Mongoose allows us to define our models in the form of a schema, along with a simple to use API that abstracts away a lot of the pain of working directly with the MongoDB driver.

First, we will create a Book schema using MongooseJS. We will use string data types to add a title, author and description. Next, we will build a simple server using Express.js. Then we will build 4 routes to query, update and delete Books from our Schema. We will use Postman to perform actions on these routes and check the results in our browser.

What You Will Learn

  • Build CRUD Applications
  • Create Mongoose Schemas
  • Design Routes using Express.js
  • Create a Server using Express.js
  • Build a RESTful API

Transcripts

1. Project Overview: Hello and welcome to our first project building a simple crude up using No Js Express and Mongoose will begin this project with the introduction what Mongoose is and how we can use its well documented A P I to communicate easily with Mongo. Db. Our crowd application will consist of building out a book schema to be used for creating, reading, updating and leading books. We'll be using express Js to create routes that will form the basis for a rest ful a p. I will be using postman to perform actions on the routes that we've created, and we'll use our browser to confirm that changes have been made. Even though this isn't a flash application, you will learn the essential building blocks that you will end up using over and over again in all future applications you build with no jazz 2. Understanding Mongoose: this video will cover the basics of what Mongoose is and how we use it. Mongu she s is a node module that makes it easy for us to interact with mongo db It provides us an abstraction in the form of an A p I for creating schema as and manipulating data. The schema creates key and value pairs for the different data types available to us within mongo. DB will be going over the mongoose, a p I in detail and you can learn more now by checking out the documentation located at Mongu SJs dot com So what does mongoose do? Mongers creates an easy to use object reference when interacting with mongo DB. And what makes mongers great is that our database gets modeled within our code. How do we use mongoose? First we require in the Mongoose module. Next we set a variable reference to a mongoose schema and then we create our schema. Now, in order to use our schema and other files, we need to create an instance of the schema. And when using mongoose, we call this instance a model. So now I can use the handy module thought exports method given to me by node. And now I'm able to use my new schema and other files simply by requiring this one. With the scheme all set up, All we need to do now is establish a connection to Mongo DB and this is very simple. First, we create a variable assigned to our instance of the database. A DP name can be anything that you want. It just represents the name of the database that we use. Then we just use ma goose dot connect to connect to it and just make sure that you always remember toe halve Maan God running in your terminal, otherwise so get in error. 3. Mongoose Schema: Let's now build a Mongu schema in a later video will be digging into the Mongols AP I more detail. But for now we'll tackle the most used aspect of monkeys, which is the creation and usage of schemers. You can find out more about building these schemers and using different data types on the Mongoose Documents page. We'll start out by creating a file called book dot model dot Js. So I'm gonna navigate into an examples folder, navigate into their so we'll be building a book, schema or model, and you can think of a model as the basis of a database architecture. So each scheme that we build will have this file name structure, and I'll generally refer to either the model or the schema, which could be used pretty interchangeably. So we'll start off by defining a couple variables. First, we make sure that we require Mongoose, so we're going to be creating a book schema, and a scheme is a method that we get from Mongoose. We're going to be exporting our model for usage in other files so we can go ahead and do that. Now we can say module dot exports equals R Mongoose model and we're going to Neymar Schema book. We're gonna pass in the name of our schema, which will create now, which is book schema. There will say book schema Equals and new schema, which again is a mongoose schema. There's two ways that we can set up our key value pair fields. We can either set them up directly like this, so this implicitly sets our data type to string. Or we can pass in an object for the data type. It's always referenced as type when I'm creating a scheme all typically used. The first method or way of defining our data types, however, mongers gives us the ability to add in optional fields. So one kind of option of field is the required feel that we can set to true or false, the default. Is it the false meaning that this field is required in order for this model to be saved? Another often used field is unique. You'll see this lot of times used when someone is building up. A scheme of that requires an email, so you want to make sure that the email that the user has submitted has only been used once Here's another kind of optional feel that's called default. So this is used in case a user hasn't input it. Anything in to the field or nothing has been generated. We can set a default key to make sure that something gets saved. You'll see this use a lot of the time with dates setting a default to day thought now, which makes sure that the date is being saved as an eye. So date for right now we can set the keywords as an array published can be a bullying so it could be true or false. Published or not, we can set. The author is a type scheme of the object I D, which will reference another schema, a model that we've created in another file. So we always need to have some kind of a reference and will name the reference as the user . So when this model of saved it will grab the reference of the user model and added into this field. So if we were to reference our book model somewhere else, saying scheme of that object idea, we would use book as the reference. Sometimes you'll see the type as schema thought type the object i d. Essentially, it's the same thing. It's just in alternative way of saying schema dot object idea. We can also add embedded sub documents and embedded a raise. So when embedded sub document would look something like this. So this would be something that you might see in an Amazon type store where, underneath the details were listing the book model number. Whether or not it's a hardcover, the number of reviews and the ranking within a category. The data within the sub documents can be retrieved using dot notation. So in this example, we would display the object using something like data dot detail dot model number in order to retrieve that information. So in this video we talked about the different data types that we can create within Mongo DB, and we provide an example of what a Magoo schema might look like when we're creating these different models. In the next video, we'll see how we can use different fine methods for retrieving data from a model 4. CRUD App Part 1: the last video we learned a little bit about Mongoose, including how to create schema as and set up a connection in this lecture will start using Mongoose along with express and no Js to query objects and to display results. So in this lecture, we're gonna be building a mini app Weaken, start up by navigating into a folder where you want your application to be. So I'm gonna copy this folder location into my terminal. I'm going to create a new directory. I'm gonna call this Mongoose E X. I'm going to CD into that folder. Now you can see the folders created, and I'm going to go into it. Now I'm going to create a couple of files for this folder. I'm going to create an APP Jazz fall, and I'm gonna also create a model. So our model will be called book dot model Dodge s. It's very common to capitalize the name of your model. Now I'm gonna create a package dot Jason by using in PM In it, enter just anything into these, the entry point will look towards our f Js file. So we open up our package Dodge a song we could see, it's pretty much empty, but it just gives us the initial scaffold. And I'm gonna install three in PM modules for this project. And those modules that are installed will show up in this package that chase on file so I can say NPM install dash, dash, save It will be using Express Mongoose and body Poor sir came with those added Let's open up our app Js file. The first thing that I'm going to do is set up a very simple server and then test that it's running. So I set up an instance of express using our app variable that will allow us to add routes and starter server body parts or will allow us to grab elements from the front end as well . Aziz parameters within our girl and, of course, will require Mongoose going to sign a variable to report and I'm gonna name in 80 80. So, in order to access our server in a browser will navigate to local host Dash 80 80 and to starter server. All we have to do is say app dot listen and passing our port, I'm also going to add in a callback function toe. Let us know that our server has been started. You know, I'm gonna save this file and going to my no terminal, and I will say node up, which should fire up our server. And we also get the message app listening on Port 80 80. So our servers working and it's listening on our port. Now, the next thing that I want to do is create our book model schema. Remember, we create a book dot model dot Js file. The first thing that will do is require mongers. Second thing that will do is create a variable for a manga schema. And just like in our example, I will create a book schema going to create three fields for a book schema, a title and author and a category. And finally, I'm going to export our book model schema so that we can use it in other files. I'm going to save this file and now I'm going to require this file in my app Js file. The difference between requiring files in our app, Jess file and requiring node modules is that we have to specify the location. So we're requiring in this book dot mall dot Js file that's located in the same location as our EP Jess Files located with their schema created. We can go on to creating a location for a database and connecting to that database using Mongu stock Connect. So just like in our example, I'm gonna set it variable for a database. And I'm gonna keep on using the same data base that we used in the previous example, which is a database called example. And below that, I'm going to use Mongu stock necked to open up our mongo db local instance and will connect to the state of base Example. So now I'm going to save this file and I'm going to try to start our server again. First, I'll kill the server and then restart it by typing in no tap and we'll see that we get an air or thrown. So it did start a per server, But then we immediately got an error and then our server shut down. So you always see the same kind of error whenever we forget to start our mon God instance. So now if we go back and type in Maan got it will start up our Mongo server and Now when we go back to restart our server, it should work. Okay, so we get the message listening on Port 80 80 without our error message and with Ma got started, were also able to log into our show. So now we're logged into our show and we have our server running. Let's use our example database and let's show collections in our example database. So one very interesting thing to note is the fact that books got automatically generated when we loaded up our notes server. Even though our schema is called book. So our scheme is called book, and once we started our server, we automatically got a new collection named Books. And when we go to db dot Bookstop fine, it's empty. So I can say db dot Bookstop Fine, Not pretty. And it's still empty, so there's nothing in there, but it was automatically generated. And what's most interesting is the fact that is plural ized. So whenever you're creating a schema, mongo DB will automatically plural eyes the name of the schema that you create. So at this point, I'm going to insert three books into our books collection, okay? And these are the books that I'm gonna insert and provide you this file. You could just copy it over now, basically is gonna copy this into our Margo Shell so it's gonna insert each one of these books into our books. Collection says Right results once. Now, if I say db that books don't find out pretty, it should show these three books that I just added, and it does. So now we have three books that we can find and read and update. So now we're going to add a couple of routes for retrieving all the books in a database and for retrieving just one book from our database that we define. In order to do that, we'll be using express, and we'll be using the app dot get method. I do have a free course on express basics or fundamentals that you can watch to learn a little bit more about some of the stuff that will be talking about. But for now, it's it's really easy to set up in use routes when you do is specify the location where we want the right to be, and then we can pass in Callback, which takes a request in response object request is anything that we get back from the user , such as when they're typing something into an input field. And we want to get that response, or rez is what we give to the user. So we can say rose dot send and we can pass on a message. So here I'm tuna, passing a message so that when a user navigates to our index route location, they'll see this message happy to be here. So now if I save this file now, I'm going to restart our app. Now, if I navigate to local host 80 80 I should see this message. Okay, great. And I see the message happy to be here, So that indicates to us that are expressed. Routing is working. So the first route that I'm gonna create is going to get all the books from our database and display them on a Web page in Jason format. So in order to do that, all I need to do it's a book that I find so booked, all fine, we'll use our model that we've defined up above, and then it will pass in the find method within find we could pass in anything that we want , so we could specify with the name with an I. D. If we don't specify anything, meaning we just put in an empty object, we will get back everything that's within their. So if we take a look at Magoo's queries, you can see a couple of examples find one will be using in the next example. But below that, we have find you can see how they're passing in specifically what they're looking for. So occupation, age, the limiting, their sorting and then finally there, calling execute right, execute with the call back. So that's what we're going to do after we find all of the books we're going to execute so you don't execute. And it's very standard to pass in two parameters and error and the response of what we're getting. So what we're gonna get back is a list of all the books, and this is basically a variable, so books could be results. It could be anything that you want, but we're gonna call it books. The Miss it. This is a callback right call back there receives two parameters. First, we're gonna check if there's an air. So if there's an error will respond by sending an air message has occurred. And if there isn't an error, that means that we were able to get back all over books and will send a Jason response listing out all the books. And we also logged the books in our consuls that we can see them that way as well. So now when I navigate over to this route, which is gonna be local host 80 80 slash of books, I should get a Jason response with the three books that we've inserted, as well as a message in a consul with the three books. So now if I say that and then restart our server, I have an error on 25. So this, yeah, cut up listening on Port 80 80. So now if I go to a local host, 80 80 slash books. Okay, look, now I get the print out of the three books that I've added, and let's also check our consul, and we can also see that we get a log of the three books that were added. Okay, so that's what we were hoping for. 5. CRUD App Part 2: Now I want to be able to retrieve one book in particular. So we can do that using the fine one method that is a mongoose query that we saw right here . And for this one will be using body part, sir. So this is a again, a very standard way of passing around data is to use the parameters and the parameters is just what we find in here. Okay, so we're gonna pass in ah, colon dot i dy which will translate to something like this. Right? And this is going to be This is gonna be the object. I d. Okay, so we're basically gonna pass in the object. I d. Right here. So when I navigate here, it's going to give me back this specific book, the idea, the title, the author and the category. So it's gonna be books and a parameter, which will name I d. We'll take a request in response. Object as the callback. A law getting one book. I want to use the fine one method from mongoose. So here I can pass in key value, pair of what I'm looking for. So I'm going to match up with the underscore i d again the underscore ideas. What we just talked about it is right here, right? So I'm going to pass in this right, and I'm not gonna hard quote it. I'm going to use body parts or by saying requests. Thought caroms. I thought I d right. So this i d is this I d right? We're just passing it in. And then just like above, I'm going to execute it with a callback function that takes an ear and the book that we get back. So if there's an air or respond with the error, otherwise we're gonna get back our book and we'll log the fact that we got it back and I'll print just a Jason indicating that we got her book back. Okay, so now I save this new route. Now I'm going to restart my note application. It's listening. Import 80 80. Now, I should be able to copy and paste this in right here, and it's working. So I put into the euro the i d of the book that we're looking for, and I got back the book. So now you should have a better idea of how to set up mongoose with no Js had to create some routes and how to get back data from your mongo db database 6. CRUD App Part 3: So far, we've looked at how to find all our books and how to find a single book from our collection . In this video, we'll see how you can post or at a book to our database, updated book and the little book. So the first thing that we need to do is we need to use body Parsa So currently using body part, sir, to get elements from the parameters. But in order to use body part, sir and parse Jason or you RL's, we need to explicitly state that that's how we want to use body part, sir. So body part, sir dot Jason will allow us the parse Jason elements your own coated will allow us to give and receive body elements through the your l so that will be able to use this with postman . So, as mentioned in this example, we are gonna be using postman and postman. You confined right here. It's a chrome extension at on and allows us to do post put get deletes two r A p i routes. And with postman, I could do a get call to the books route that we created and when sending a get request I can get back all the books that I have submitted to our database. So in these upcoming examples will be using Postman and I'll be using the post and delete methods in order to add new books, update books and elite books. So in this video, I'm going to show you two different ways that we can add a post route. It's the first way, is what you probably find more often. We'll start off with our standard route that we want to use, so we're going to still be using our book route. But we're just going to be posting to this route instead of getting on the route and will pass in our request in response objects. So there's two different patterns that you Tennessee. The examples. The 1st 1 is that we can use the create methods. So Mongoose has a create method that we can see right here so we could say, book dark, create and then pass in the body of what we want to create with a call back and will actually be looking at this as our second example. Since it's not used is often what you what you'll see used more often is will define a variable Which references are schema. So we'll say new book equals a new book Schema. So now I'm able to explicitly attach our book fields to body elements that we can define. So within our books schema, we have a title we haven't author and we have a category. So I'm going to define those will have a title and author and a category. So this will be request our party, that title Questar body, that author and request our body dot category So these refer to the keys that we're gonna be passing in when we're saving a new book. The value will obviously be the names of the title of the author in the category. So after passing those in, we will call a save method and we'll use our sander. If there's an error, will pass an error. And if we don't have an error than will log the book that got saved and we will send it back to our front end or, in this case, the Postman. So we'll say that and I should see my server getting restarted, which it does. So now what I'm gonna do in Postman is and wouldn't send a post message to our route. So our route is still 80 80 slash book, and we're gonna be using this form, your oral and coded. Now we will be adding key value pairs here. So we're gonna add her title, and we'll nave it. What? We dick author. It's probably Hemingway in category se fish tails. So now when I click send If I set up this route correctly as a post route, then it should show up right below here, okay? And it does. So it looks like our book up posted, and we got back a Jason response, and I also logged it so we can see that it gets logged to our consul. And if that wasn't enough confirmation, we will go and hit our books route and we can see that are book Moby Dick. God added as a new book. So this is the more predominantly used way of adding or posting to a route. So the other way is just the passing request, our body or the whole thing. And this also works so well, make another route and we'll just call this slash book to, and it would also be a post will do a request and response objects so in this route will use the example who we can say booked our create. So Crate is a method that we found on Mongoose right here, and we can just pass in the whole body instead of individual pieces of body otherwise will look the same. We're going to pass in a call back with an air, and the book that we added, if there's an error, will display the air. Otherwise, we'll log the book and send a response. So this should work the same way as the previous example, and it looks a little cleaner takes up less lines, less space, but it's a little more error prone. At the same time, we'll change this up a little bit and we'll post and it works just the same. So example to Hemingway, Jr If you're saga, get posted, and if I refresh our book stock, get right, we can see that I could suppose that it also and we also get it shone in our consul 7. CRUD App Part 4: So now let's see how we can update one of her books. And for this will be using the find one and update method, which can be found right here in our Mongu SJs stocks. And this is one way to update our model. For this example, we will use our find one and update method inside of a put a P I call toe a book colon I d route. So this will look a lot like our when we're finding one particular book. We're doing the same thing. We're still finding one book, but we're gonna be updating it Also going to find a book and update and will pass in what we're looking for. So it's the same as the original find where will pass in underscore i d. And we'll set it equal to wreck top parents that I d. So again, this idea is this I d. So let's look at the fine one. An update method. It takes conditions, update options and a call back and below. We can see an example of what's being done. Our example will look something like this. The quarry is what we've already set up. It's the underscore I d Then we want to set what it is that we're updating. So in this example, they're sitting name to Jason Bourne, and then we'll have options and a call back, so we'll actually be using all these in our example. So our query is what we've set up is this right here? Now we're going to set up what we want to update. So just like in the example given tow us, we have to pass in set. So what do we want to say? We want to set our title. And what do we want to set our title to? We're just gonna say request stop body DOT title And in this example, I'm only going to do the title, but we could easily pass in the author and category as well. The third parameter is an optional parameter. Now you'll usually see when updating and using this private er absurd, true being used. And this just lets Mongu snow that if the title, whatever it is that we passing doesn't already exist to insert it. And then finally we can use our fourth parameter, which is the callback function. No, clean this up just a little bit. We'll pass in air and new book here. And in this example, I'm just going to pass the status of two or four, which will indicate that the book got updated correctly. Okay, so that should fix my syntax. I just need extra ending curly bracket right here. So now let's test out this route and to test this out, Going to take the I d of one of our books. Take this one right here. So currently, the tile is example. So I want to change that. So I'm gonna go to book, slash the idea or a book, and I'm going to update our title to be cola's example three. And I'm going to send. And we need to change this to a put. I'm gonna send it again. Well, did get updated, but I didn't get the message in postman yet. So some statist status will just send this back. We'll change this to example four, whether it is okay, So it showed up after a little while. So if I change this to example for it still shows up in my postman as example three. But if we go back, and if we check let's see now it shows up as example for when we're getting our books. So it is working. And in this last example, I'm gonna show you how to delete a book. And for this one will be using find one and remove, which can be found right here in our manga. She s a p I to a pass in are conditions, options and a callback. So just like previously, we will create a new route and passing the i. D of our route. The second parameter is a callback. And then we can say, booked out, find one and remove. And then, just like in the previous example will say underscore i D and said it to our parameters. And in this example, we don't need any options. We can just go straight to the callback and on delete we can pass in our call back. If there's an error, will respond with the air message. Otherwise we'll just we'll just log the book and this one will respond with a two or four Save that. I'm going to grab the I d again and we'll go. And instead of a put now will be using a delete so if I send this some reason I put Look, that should be book correct. And we get our app listening and it's the same thing. That's the status method isn't working. But if we reload our books route, then this should be gone. Okay? And it did get deleted, and we can see that it was deleted from our consul log also.