I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
Before submitting a
exports.addPost = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
req.flash('errors', errors.array())
req.session.save(() => res.redirect('../addpost'));
//return res.status(400).send(errors.array());
} else {
const post = new Post();
post.title = req.body.title;
post.short_description = req.body.excerpt
post.full_text = req.body.body;
post.save(function(err){
if(err){
console.log(err);
return;
} else {
req.flash('success', "The post was successfully added");
req.session.save(() => res.redirect('/dashboard'));
}
});
}
}
messages.ejs
<% Object.keys(messages).forEach(function (type) { %>
<% messages[type].forEach(function (message) { %>
<% if (type === 'errors') {%>
<%= message.msg %>
<%} else { %>
<%= message %>
<% } %>
<% }) %>
<% }) %>
I guess this is what you intended to do