The first thing I'm going to do is fill out the code. We're going to validate the ID and we're going to send back a 404 response code if it's not valid. Up at the very top of the file I do not have an ObjectID imported so I'm going to have to go ahead and do that. Just below bodyParser, I can create a variable ObjectID, and set that equal to the return result from require; we're requiring the mongodb library. Now that we have ObjectID in place, we can go ahead and use it. We'll write an if statement, if (ObjectID.isValid()). Now, obviously we only want to run this code if it's not valid, so I'm going to flip the return result using an exclamation mark, and then I'm going to pass id in. Now we have an if condition that's only going to pass if the ID, the one that got passed in as the URL parameter, was not valid. In that case we're going to use return to prevent function execution, then I'm going to go ahead and respond using res.status, setting it equal to 404, and I'm going to call send with no arguments so I can send back an empty body. There we go, our first thing is complete. With this in place we can now go ahead and move onto creating the query:
//GET /todos/12345
app.get('/todos/:id', (req, res) => {
var id = req.params.id;
if(!ObjectID.isValid(id)) {
return res.status(404).send();
}
});
At this point we actually do have something we can test: we can pass in invalid IDs and make sure we get that 404 back. Over inside of the Terminal I ran the application using nodemon so it automatically restarted in Postman. I can rerun theĀ localhost:3000/todos/123 request and we get our 404, which is fantastic:

This is not a valid ObjectID, the condition failed, and the 404 was indeed returned.