UPDATE:
Matus Dubrava, you are right, of cores, but I changed that line to res.redirect('/post/show/' + pid); and it still does not work. The route is http://localhost:3000/post/edit/5d0fddd730d83f0c32c1e0ca
The snippet responsible with showing an individual post does work. It is:
app.get('/post/show/:id', function(req, res){
Post.findById(req.params.id, function(err, post){
res.render('single_post.pug', {
post: post
});
});
});
Yet, redirecting with res.redirect('/post/show/' + pid); does not work.
I am working on a basic CRUD application with Node, MongoDB and Express. I use Jade for the views ad Bootstrap 4 for styling.
There is an edit post functionality that works ok, but my update has a bug I have not been able to spot and fix:
The edit form view:
h2 #{title}
form(action="/post/edit/" + post._id, method="POST")
.form-group
input.form-control(type="hidden", name="post_id", value=post.post_id)
.form-group
input.form-control(type="text", name="title", placeholder="Post title" value=post.title)
.form-group
input.form-control(type="text", name="category", placeholder="Post category" value=post.category)
.form-group
textarea.form-control(rows="5", name="body")= post.body
.form-group
input.btn.btn-sm.btn-block.btn-primary(type="submit", value="Update")
The code corresponding to edit and update actions:
// Edit post
app.get('/post/edit/:id', function(req, res){
Post.findById(req.params.id, function(err, post){
res.render('edit_post.pug', {
post: post
});
});
});
// Update post
app.post('/post/edit/:id', function(req, res){
let post = {};
post.pid = req.body.post_id;
post.title = req.body.title;
post.category = req.body.category;
post.body = req.body.body;
let query = {_id:req.params.id}
Post.update(query, post, function(err){
if (err) {
console.log(err);
return;
} else {
res.redirect('/post/show/' + pid);
}
});
});
The post does get updated but:
- The redirect url is
http://localhost:3000/post/show/:pid; - The browser shows
Cannot read property 'title' of undefined.
Where is my mistake?
PS: I can't add all the code here so I have put together this paste-bin.
from Express.js CRUD application bug: update function does wrong redirect
No comments:
Post a Comment