Validating an ObjectID

Now, the last thing I want to talk about is how to validate an ObjectID. What we've done so far is we've created a valid ObjectID. It's just of a value that is not in the collection, but if we were to do something like tack on two 1s, we would actually have an invalid ID which is going to cause errors in the program. Now, you might wonder why this would ever happen, but it could happen because the user is the one specifying the ID. We're going to add a catch call onto findById. We're going to get that error and simply print it to the screen using console.log:

Todo.findById(id).then((todo) => { 
  if(!todo) { 
    return console.log('Id not found'); 
  console.log('Todo By Id', todo); 
}).catch((e) => console.log(e));

Now, to ...

Get Advanced Node.js Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.