Reputation: 13
I'm building a movie database with MongoDB, node.js, and express. I have two routes currently, one that renders a page that displays all of the movies in the database, and another that displays information for an individual movie. The problem is when rendering the page for each individual movie with ejs, I am not able to parse the object that is passed, which holds things like the title, the year, and a few arrays of images.
When rendering the all movies page, I am able to parse the object and display it with ejs. So I am not sure what the difference between the two routes is.
Schema for Movie
const movieSchema = new mongoose.Schema({
name: String,
date: String,
production: String,
cast: String,
remarks: String,
lobbyCards: Array,
filmStills: [
{
url: String,
caption: String
}
],
behindStills: [
{
url: String,
caption: String
}
],
advertising: [
{
url: String,
caption: String
}
]
});
Here are the two routes:
All Movies
app.get('/movies', (req, res) => {
movie.find({}, (err, movies) => {
if (err) {
console.log(err);
} else {
res.render('movies', { movies: movies });
// console.log(movies);
}
});
});
Individual Movie
app.get('/movies/:name', (req, res) => {
movie.find({ name: req.params.name }, (err, movieData) => {
if (err) {
console.log(err);
} else {
res.render('show', { movieData: movieData });
}
});
});
If I console.log(movieData) it is logged as an array.
This is what renders from the All films page All films
This is what renders from the Individual Film Page Individual film
Upvotes: 1
Views: 300
Reputation: 24555
If you want to get a single document from the db, you probably want to use:
movie.findOne({ name: req.params.name }, (err, movieData) => { ... }
With .find()
an array is returned even when only one document matches the query which is why the movie object cannot be displayed in your ejs.
Upvotes: 3