Day Log App in Node.js Part 6: Delete a DayLog

This post will discuss how to implement the deletion a DayLog.

Table of Contents

Development

Each DayLog is removable and this should be accessible from the home page with the “Delete” button in the table.

DayLog index page - not empty table

NOTE: I decided to exclude the BDD testing in this part because I am having problems in implementing the edit test cases.

In /views/daylog/index.ejs. update the action path of the “Delete” button form from:

<form action="/<%= daylog.slug %>/delete" method="POST">

to the pattern /daylog/:slug/delete:

<form action="/daylog/<%= daylog.slug %>/delete" method="POST">

In addtion the method override for DELETE is already in the form.

<input type='hidden' value='DELETE' name='_method'>

Add the route

NOTE: Make sure that there’s an exisiting DayLog in the database.

If we click the “Delete” button right now it should return a 404 so this route should be added:

router.delete('/:slug/delete', DayLogController.delete);

This should recognize the pattern /daylog/:slug/delete as intended.

Delete the DayLog

Add the method delete:

delete: (req, res) => {
    DayLogModel.findOne({ "slug": req.url.split("/")[1] },
        (err, daylog) => {
            if(err) return console.error(err);

            daylog.remove((err, daylog) => {
                if(err) return console.error(err);

                console.info('Deleting: "' + daylog.title + '"');

                res.format({
                    html: () => { res.redirect("/daylog"); }
                });
            });
        }
    );
}

Re-run the application and deleting an entry in the table should remove it afterwards.

References

Twitter, LinkedIn