I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
Before submitting a new post, of course, I have to validate the form entries. I use express-validator version 6.3.0.
My addPost controller:
exports.addPost = (req, res, next) => {
// Form validation rules
check('title', 'The title field id required')
.not()
.isEmpty();
check('excerpt', 'The excerpt field id required')
.not()
.isEmpty();
check('body', 'The full text field id required')
.not()
.isEmpty();
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors.array());
}
if (!errors.isEmpty()) {
res.render('admin/addpost', {
layout: 'admin/layout',
website_name: 'MEAN Blog',
page_heading: 'Dashboard',
page_subheading: 'Add New Post',
errors: errors
});
req.flash('danger', errors);
req.session.save(() => res.redirect('/dashboard'));
} 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'));
}
});
}
}
The Post model:
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
short_description: {
type: String,
required: true
},
full_text: {
type: String,
required: true
},
post_image: {
type: String,
required: false
},
updated_at: {
type: Date,
default: Date.now()
},
created_at: {
type: Date,
default: Date.now()
}
});
The error messages are nor rendered in the view, which looks like this:
<div id="messages" class="text-center">
<% Object.keys(messages).forEach(function (type) { %>
<% messages[type].forEach(function (message) { %>
<div class="alert alert-<%= type %>"><%= message %></div>
<% }) %>
<% }) %>
</div>
UPDATE:
The index.js file in the root has this code:
const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const path = require("path");
const morgan = require("morgan");
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressLayouts = require("express-ejs-layouts");
const flash = require("express-flash");
const session = require("express-session");
const app = express();
dotenv.config();
//Conect to MONGODB
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("conected");
});
mongoose.connection.on("error", err => {
console.log(`DB connection error: ${err.message}`);
});
// Set static directory
app.use(express.static(path.join(__dirname, "public")));
// Set views directory
app.set("views", path.join(__dirname, "views"));
// Set view engine
app.set("view engine", "ejs");
// Use Express Layouts
app.use(expressLayouts);
// Morgan Middleware
app.use(morgan("dev"));
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
// Express Sessions Middleware
app.use(session({
secret: '123',
resave: true,
saveUninitialized: true
}));
// Express Messages Middleware
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Bring the Dashboard
const dashboardRoute = require("./routes/admin/dashboard");
// Get Dashboard Routes
app.use('/dashboard', dashboardRoute);
What am I doing wrong?
See Question&Answers more detail:
os