0

I have this error when I'm trying to run this code:

Error UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "main.css" (type string) at path "_id" for model "FILM"

app.get('/films/:id', (req, res) => {
  const id = req.params['id'];
  FILM
    .findById(id)
    .then(item => res.render('template.ejs', {item}));   
});

template.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="main.css">
  <title>Template</title>
</head>
<body>
  <header class="header">
    <%- include('partials/header.ejs') %> 
  </header>
</body>
</html>

What does main.css do in req.params?

GoRvAnOv
  • 13
  • 2
  • Is `template.ejs` inside of a directory named `films` ? – L'Ange Déchu Jul 21 '22 at 09:59
  • No, films it's films.ejs file – GoRvAnOv Jul 21 '22 at 10:21
  • 2
    In `template.ejs`, at the `link` tag, try to add a forward slash (`/`) before "`main.css`" so it looks like this: `href="/main.css"` – L'Ange Déchu Jul 21 '22 at 11:03
  • You need to show how your server and routes are setup - I suspect that the import of your `main.css` file in the `template.ejs` file is somehow relative to the `/films` route - so perhaps your first request for `/films/` actually succeeds and then a second one is sent to `/films/main.css` to try and retrieve the CSS file. Try modify the path to the `main.css` file (or even remove the import for it) to see if that is the cause – jeeves Jul 21 '22 at 11:04
  • @jeeves if i delete main.css the problem goes away, if i try do request /films/something i am getting an error CastError: Cast to ObjectId failed for value "something" (type string) at path "_id" for model "FILM" – GoRvAnOv Jul 21 '22 at 22:29
  • `something` is not a valid `ObjectId` (assuming you're using a mongodb database). ObjectID has a strict string representation format – Phil Jul 22 '22 at 04:40

0 Answers0