Wednesday, 3 July 2019

Express.js CRUD application bug: update function does wrong redirect

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 podt
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:

  1. The redirect url is http://localhost:3000/post/show/:pid;
  2. The browser shows Cannot read property 'title' of undefined.

Where is my mistake?



from Express.js CRUD application bug: update function does wrong redirect

No comments:

Post a Comment