Introduction to MongoDB

Build a REST API Solution

Scott Moss

Scott Moss

Superfilter AI
Introduction to MongoDB

Check out a free preview of the full Introduction to MongoDB course

The "Build a REST API Solution" Lesson is part of the full, Introduction to MongoDB course featured in this preview video. Here's what you'd learn in this lesson:

Scott live codes the solution to the previous exercise.

Preview
Close

Transcript from the "Build a REST API Solution" Lesson

[00:00:00]
>> Scott Moss: Hopefully everybody had a chance to integrate Mongo and Mongoose with an Express application. Like I said, it was very much like the example that I did, just a slightly different model. Obviously you had to fill out these functions, there might have even been one or two things you had to add.

[00:00:15]
But at the end of the day, it was pretty simple. So I'm gonna walk through this exercise, before I start, does anybody have any questions specifically to this exercise that came up? Maybe they wanna ask now that they have some experience building a full blown API.
>> Scott Moss: No, all right, we'll hop right into it.

[00:00:32]
So the first one is I wanna be able to get it Todo by an ID. Well, the ID is gonna be on the req.param.id. That's very specific to express. You don't need to know what that is. That's why I put that there for you, so you didn't have to figure that out.

[00:00:44]
But, basically anything with a colon in front of it's gonna be a parameter. And you can access a parameter by name, by whatever name it is here. So if this was called I, then this would be called I. And that's how Express works, so you can do parameters.

[00:00:58]
So once we have that ID, I'm just gonna go ahead and say give me the Todo = await. Todo.findById and then past id, do a .lean. Oops. Why is it a div there? That was ridiculous. .exec. So now we have the Todo, I'm just gonna say res.status. Res is short for response with 200 status code, and I'm gonna send back some json over todo.

[00:01:36]
So this will work. So let's test this and see all of this will work. There's some nuances here. So let's see what that is. But if I run this, I got my URL here. I'm gonna go over to Insomnia. I'll paste that URL here. I'm gonna do a GET request to /todo.

[00:01:55]
I'm just gonna put some random thing here, all right? And then we'll hit send. And you can see, it's just going to load and load, it's hanging. There's no reason why this service would take this long to respond. Usually, when you see it that means something blew up and it's not telling you.

[00:02:11]
So the way you would fix this. Actually, let's look at the error so you kinda understand. As you can see, what actually happens is we have an unhandled promise rejection warning reference error. In this case it's saying ID is not defined, that's probably because I typed in the wrong ID.

[00:02:26]
So, let's fix that. But even after I fix that, you're gonna get the same error if I run this.
>> Scott Moss: It's still gonna hang, it's still gonna break, and that's because the actual error wasn't that typo that I had. Well, actually it was because it's trying to cast the value of that parameter to an object ID.

[00:02:45]
The way ID's work with Mongo, like I told you they're all object IDs. So before it actually tries to do the query for a buy an ID, it's going to take the value of the ID that you gave it and it is going to try to see if it is a valid object ID and if it's not it's just gonna fail right there, and that's what's happening.

[00:03:02]
So whenever you see a cast error that means you gave it a different value type than it's expecting. Anything find by ID is expecting an object ID always, unless you go and change what an ID is for a schema, which you can do. Which we did not talk about cuz it's really advanced.

[00:03:20]
But by default it's always an object ID. So that's why this failed. So you couldn't just come in here and just write something like that. So that's one thing. Another thing, is why is the server hanging, the server should just send back an error message instead of hanging like that.

[00:03:33]
That's kind of more a server topic type thing, but basically the answer is to that, whenever you're doing Async 08, you have to try and catch your errors, right? Cuz it's hanging because we didn't handle the error that this was. So the way you would fix that is you would a try-catch around this Async 08 or if you're using promises, just use a dot catch.

[00:03:59]
>> Scott Moss: So I would catch that and now I would say if it freaked out, at least it would send back a 500, whatever, status code. I'll just send that back. So if I restart that,
>> Scott Moss: Restart the server and then go back. At least now I get a 500.

[00:04:17]
It just responds immediately saying, yeah, that's just not gonna work. You could see I got a 500 internal server error. So that's how you fix that. And now our server just doesn't hang and we can do other requests. So obviously this isn't going to work until we can send back a real ID.

[00:04:33]
So let's get to the next part. We can create something then we can grab one of those IDs and then we'll pass it to this and we'll see if it works. But before that we'll get all todos which doesn't take any parameters. So this would just be pretty free.

[00:04:46]
So we'll just do the same thing to a try-catch here.
>> Scott Moss: And I'll just do the same thing for now. We'll just send back all 500s for now. And then what we'll do here is we'll just say, I can actually just do all this in one line. I can say res.status(200) or 200 for GET, And then .json.

[00:05:11]
And then I can just await right here. And I can just say, todo.find.lean.exec.
>> Scott Moss: So this is giving me all the todos. Wild card, I'm gonna wait it right in line. That's sweet thing by the way, you can just do it all in one line. So I was giving you that and then we'll restart server and we'll try that out.

[00:05:43]
So I'm expecting to get back an empty array, if I do this. It's todos.
>> Scott Moss: Cool, so I do, I get back an empty the array because the database didn't find anything and the database just returned an empty array, so that's what I've got back. And, onto the part where we actually can create a todo, so our arguments are req, response.

[00:06:11]
We get the todo created by passing up an object that has a todo property on it. And we know a todo has, if we go look at the model, it has a message that's unique and required in a complete that's default. So all we really need is a message.

[00:06:26]
So long as you send back an object that has a message property you're pretty good. So we'll do the same thing, we try-catch this.
>> Scott Moss: And if we couldn't do it, we'll just say res.status, 500.send, boom. And then now we'll try to create this so we'll say todo equals await, todo.create and we'll pass in the todotocreate.

[00:06:55]
And what we'll do is we'll res.status(201).json, and we'll do todo.json to get the JSON representation of it.
>> Scott Moss: So we'll do that. Restart the server. Oops, where is that? How did that happen?
>> Scott Moss: Cool, so now we'll go back here. We'll do a post request to the route is /todo.

[00:07:30]
And we'll add some json, it's looking for a todo property on the body, so I'll add a todo property here. And I know a todo, the only requirement that it has is a message, so I'll add a message and I'll just say hello there. So then I will send that.

[00:07:53]
I get a 500 error because, it blew up here. So, whatever I sent, it didn't like it. So, the way we get around that is we need to see where the error is. So we'll log this error and we'll restart and see what happens. I'm guessing its the way that I'm sending it up from Insomnia, it's doing some type of formatting other than json that I'm not aware of.

[00:08:19]
So we'll try that again and we'll send it, we'll look at the error. It looks like it's just a duplicate key on,
>> Scott Moss: Hello there. So, it's supposed to be unique so let me try that again do another one of that and clear the console, hit send, still errored out.

[00:08:43]
So this one says, it's not letting me use two jsons. It's not liking that. That's weird.
>> Student: Is it two Jason?
>> Scott Moss: Yeah, I'm sorry. I just mistyped that. It is tojson. I just put json. There we go.
>> [SOUND]
>> Student2: Can we not put json strings into the json response sender?

[00:09:09]
>> Scott Moss: This right here .json?
>> Student2: Yeah, don't we just put full objects into that?
>> Scott Moss: We do, yeah. It converts it to json for us. Okay, so you're asking like to do that json doesn't that give us back like json? It's kinda misleading, it does. It actually gives us back an object.

[00:09:27]
I know, so [LAUGH] it gives us back an object. That's why sometimes I will use toObjects instead. Yeah, they both kinda do the same thing. Very misleading, I know, it's kind of silly, but no, it gives you back an object By the way, technically an object is JSON.

[00:09:46]
JSON stands for JavaScript Object Notation, and technically a JavaScript object is a JavaScript Object Notation, so it's not wrong.
>> Student3: I think JSON like text JSON right there.
>> Scott Moss: Yes, of course, yeah. But I guess it's the way they rationalize it. It's like hey, it's not wrong, you know?

[00:10:01]
Who's gonna complain about that? We did. [LAUGH] So, we'll send that, I've got to change the name. See those validations, how awesome they come in handy. Okay, now we send that. Cool, there we go. So now we created a todo and here we go, we've got the ID, so I'm gonna grab the ID and then now, I'm gonna be able to.

[00:10:26]
First, let's just do all todos and we should get back at least one of them. And we get three now cuz I created so many of them. So now we got three of them, cuz I did those duplicate requests. And now we have three todos. And then just to get one, which was /todo/the ID.

[00:10:44]
So I paste the ID in there. And I'm just gonna send it, and I get back that one to do.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now