Warning when passing id that doesnt exsits in collection

When using this code as suggested in solution for exersice I get an " UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value “xxxxx” at path “_id” for model “Genre”" when I pass a id that doesnt exsits in the collection to this code…

router.put('/:id', async (req, res) => {
const { error } = validateGenre(req.body); 
if (error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findByIdAndUpdate(req.params.id, { name: req.body.name }, {
  new: true
if (!genre) return res.status(404).send('The genre with the given ID was not found.');


I know I use a later version of mongoose but what do I need to update in order to handle this error?

The issue is that validateGenre doesn’t validate the _id.

I believe Mosh briefly talks about the issue later in the course. If you don’t want to wait, just update your models/genre.js file:

const Joi = require('joi-oid');  // add this to the top of the file

// replace the validateGenre function
function validateGenre(genre) {
  const schema = {
    id: Joi.objectId(),
    name: Joi.string().min(5).max(50).required()

  return Joi.validate(genre, schema);