0
votes

I am trying to retrieve data from mongo by the id, it works well when, however when I add an external link, like a style file or a script file I get this error message.

message: 'Cast to ObjectId failed for value "script.js" at path "_id" for model "Blog"', name: 'CastError', stringValue: '"script.js"', kind: 'ObjectId', value: 'script.js', path: '_id', reason: undefined, model:

const express  = require('express'),
  ejs      = require('ejs'),
  bodyParser = require('body-parser'),
  Blog     = require('./models/blog');

const app   = express(),
      port  = 5000; 

// mongoose.connect('mongodb://localhost/blog_v1', {useMongoClient: true});
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', (req, res) => {

  Blog.find({},(error, blogs) => {
    if(error) {
      console.log(`something went wrong ${error}`);
    } else {
      // console.log(blogs);
      res.render('home', {blogs: blogs});
    }
  });
});

// findById or find({'_id': 'id'})
app.get('/posts/:id', (req, res) => {
  Blog.findById(req.params.id, (error, foundPost) => {
    if(error) {
      console.log(error);
      console.log(req.params.id);
    } else {
      res.render('posts', {foundPost: foundPost});
      console.log(req.params.id);
    }
  });

});



app.listen(process.env.PORT || 5000, () => {
  console.log(`Server is up on port ${port}`);
});
1

1 Answers

0
votes

it turned out I had only files on the public folder, so all I had to do was to create a css folder and a js folder as it was explained here:

Css not loading with req.params or maybe something else