I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
There is an "Add New Post" form of course, with an addPost() method in the controller;
exports.addPost = (req, res, next) => {
const errors = validationResult(req);
const post = new Post();
post.title = req.body.title;
post.short_description = req.body.excerpt
post.full_text = req.body.body;
console.log(post);
if (!errors.isEmpty()) {
req.flash('danger', errors.array());
req.session.save(() => res.render('admin/addpost', {
layout: 'admin/layout',
website_name: 'MEAN Blog',
page_heading: 'Dashboard',
page_subheading: 'Add New Post',
post: post
}));
} else {
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 form view:
<form action="./post/add" method="POST" class="mb-0">
<div class="form-group">
<input type="text" class="form-control" name="title" value="<%= req.body.title %>" placeholder="Title" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="excerpt" value="<%= req.body.excerpt %>" placeholder="Excerpt" />
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="body" placeholder="Full text">
<%= req.body.title%>
</textarea>
</div>
<div class="form-group mb-0">
<input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
</div>
</form>
Suppose some of the required form fields are filed-in, but not all of them.
The form view is rendered again, with error messages for the empty required fields. But the required fields that are not empty should persist their data. But they do not.
Using this syntax does not work either <input type="text" class="form-control" name="title" value="<%= post.title %>" placeholder="Title" /> even though the line console.log(post) shows this in the console, as expected:
{
updated_at: 2020-03-18T10:49:17.199Z,
created_at: 2020-03-18T10:49:17.199Z,
_id: 5e71fcbe7fafe637d8a2c831,
title: 'My Great Post',
short_description: '',
full_text: ''
}
What am I missing?
UPDATE:
The generated HTML of the form:
<form action="./post/add" method="POST" class="mb-0">
<div class="form-group">
<input type="text" class="form-control" name="title" value="" placeholder="Title">
</div>
<div class="form-group">
<input type="text" class="form-control" name="excerpt" value="" placeholder="Excerpt">
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="body" placeholder="Full text"></textarea>
</div>
<div class="form-group mb-0">
<input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
</div>
</form>
