Skip to main content
4 of 4
update wording

Shorthand Property Definition Notation

As I mentioned in an answer to one of your previous posts, The shorthand property definition notation can be used to simplify the lines like these where the key is the same as the name of the variable being referenced:

 categories: categories,
 posts: posts

To simply:

 categories,
 posts

Waiting with await

With async / await the code that is typically in the promise callback can be moved out- so take this section for example:

 const posts = await Post.find({}, (err, posts) => {
     if (err) {
             console.log('Error: ', err);
         } else {
             res.render('admin/index', {
                 layout: 'admin/layout',
                 website_name: 'MEAN Blog',
                 page_heading: 'Dashboard',
                 posts: posts
             });
         }
     }).populate('category');

I haven’t tested this code but my presumption is that the call to .populate('category') comes after the callback where res.render() is called - so that may be a bug.

It can be like simplified to something like this:

const posts = await Post.find({}).populate('category').catch(err => {
        console.log('Error: ', err);
    });
res.render('admin/index', {
    layout: 'admin/layout',
    website_name: 'MEAN Blog',
    page_heading: 'Dashboard',
    posts
});

Though maybe the call to populate the category needs to come after the value from Post.find({}) Is assigned to posts.

And similarly for the other functions called with await. This way the value assigned to posts from can be used properly.

Useless else keyword after return

In the callback to post.save():

  if (err) {
      console.log(err);
      return;
  } else {
      req.flash('success', "The post was successfully added");
      req.session.save(() => res.redirect('/dashboard'));
  }

The code in the else block can be moved out because in the first case there is a return statement. This can reduce the indentation level.

variable declared with var

The answer by CertainPerformance to your previous post recommends avoiding the var keyword. Yet this code uses it:

exports.addCategory = (req, res, next) => {

     var form = {
         categoryholder: req.body.cat_name
     };

That variable is never reassigned so it can be declared with const. And similarly for updateCategory() - it has a variable declared with var named form that never gets re-assigned.