Thursday, 18 May 2017

Dynamically loading pages with parameters dependent on mongodb data

I'm recreating a movie blog for practice and I'm trying to dynamically load pages based on what 'category' they belong to. For example, when I create a document, it has certain values, i.e. title, category, etc. The categories are 'news', 'trailers', 'movies'. What I wanted to do, instead of create html files for news, trailers and movies and then load those pages with documents found matching the specific category, I thought I could try to create one page and then load it based on documents matching the specific category. For example, if someone goes to /news, they should get a page loaded with documents of category 'news'. And if they go to /movies, they should get a page populated by documents matching 'movies'.

What I want to do is render a specific page if a matching document is found. My attempt below loads the matching url page and if that url has data matching data, it'll load it. The else statement isn't being triggered. I'm wondering if what I'm trying to do would be a good idea and, if so, what I could do to try to fix my code.

router.get('/:category', function(req, res, next){
  Post.find({"category": `${req.params.category}`}, function(err, posts){
  if(err) throw err;

  if(Post.find({ "category": { $exists: true }})){
   res.render('category', {title: `${req.params.category}`, posts: posts});
  } else {res.render('404')};
 });
});



via JosephK

No comments:

Post a Comment