Hey all,
I’m trying to make the Genre detail page and I keep getting a 404 error like the screenshot below (full error output text attached).
The URL looks like what I would expect and I see this ID in the database.
I never got an error like this:
Cast to ObjectId failed for value "59347139895ea23f9430ecbb" at path "_id" for model "Genre"
Although I attempted to use mongoose.Types.ObjectId()
to convert the ID to a usable value. But I still get the same error (I’m happy to share how I implemented this in case that would help troubleshoot.
Otherwise here’s the relevant docs from my app.
This is what I have in my genreController.js
exports.genre_detail = function (req, res, next) {
async.parallel({
genre: function (callback) {
Genre.findById(req.params.id)
.exec(callback);
},
genre_books: function (callback) {
Book.find({ 'genre': req.params.id })
.exec(callback);
},
}, function (err, results) {
if (err) { return next(err); }
if (results.genre == null) { // No results.
var err = new Error('Genre not found');
err.status = 404;
return next(err);
}
// Successful, so render
res.render('genre_detail', { title: 'Genre Detail', genre: results.genre, genre_books: results.genre_books });
});
};
Here is my genre.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var GenreSchema = new Schema({
name: { type: String, required: true, minlength: 3, maxlength: 100 }
});
// Virtual for genre's URL
GenreSchema
.virtual('url')
.get(function () {
return '/catelog/genre/' + this._id
})
// Export genre model
module.exports = mongoose.model('Genre', GenreSchema);
And here are my routes for genre:
// GET request for one Genre.
router.get('/genre/:id', genre_controller.genre_detail);
// GET request for list of all Genre.
router.get('/genres', genre_controller.genre_list);
Can someone help me see what I’m doing wrong that’s resulting in a 404 error please?
Any help is appreciated. Thanks!
John