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 instead of
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');
It can be 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
});
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 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
.