I implemented Delete functionality form express article on MDN , following the " Delete Author " Article .
It gives 404 error (Not Found) .
Here is the code:
exports.author_delete_get = asyncHandler(async (req, res, next) => {
// Get details of author and all their books (in parallel)
const [author, allBooksByAuthor] = await Promise.all([
Author.findById(req.params.id).exec(),
Book.find({ author: req.params.id }, "title summary").exec(),
]);
console.log(author);
if (author === null) {
// No results.
res.redirect("/catalog/authors");
}
res.render("author_delete", {
title: "Delete Author",
author: author,
author_books: allBooksByAuthor,
});
});
// Handle Author delete on POST
/*
exports.author_delete_post = asyncHandler(async (req,res,next)=>{
// res.send("NOT IMPLEMENTED: Author delete POSt");
// Get details of author and their books (in parallel).
const [author, allBooksByAuthor] = await Promise.all([
Author.findById(req.params.id).exec(),
Book.find( {author: req.params.id}, "title summary").exec(),
]);
if(allBooksByAuthor.length>0) {
// Author has books. Render in same way as for GET route
res.render("author_delete", {
title: "Delete Author",
author: author,
author_books: allBooksByAuthor,
});
return;
}
else {
// Author has no books . Delete object and redirect to the list of authors.
await Author.findByIdAndDelete(req.body.author.id);
res.redirect("/catalog/authors");
}
});
*/
exports.author_delete_post = asyncHandler(async (req, res, next) => {
// Get details of author and all their books (in parallel)
const [author, allBooksByAuthor] = await Promise.all([
Author.findById(req.params.id).exec(),
Book.find({ author: req.params.id }, "title summary").exec(),
]);
if (allBooksByAuthor.length > 0) {
// Author has books. Render in same way as for GET route.
res.render("author_delete", {
title: "Delete Author",
author: author,
author_books: allBooksByAuthor,
action: mongoDB,
});
return;
} else {
// Author has no books. Delete object and redirect to the list of authors.
await Author.findByIdAndDelete(req.body.author_.id);
res.redirect("/catalog/authors");
}
});
PUG template code :
extends layout
block content
h1 #{title}: #{author.name}
p= author.lifespan
if author_books.length
p #[strong Delete the following books before attempting to delete this author.]
div(style='margin-left:20px;margin-top:20px')
h4 Books
dl
each book in author_books
dt
a(href=book.url) #{book.title}
dd #{book.summary}
else
p Do you really want to delete this Author?
form(method='POST' action='')
div.form-group
input#authorid.form-control(type='hidden',name='authorid', required='true', value=author._id )
button.btn.btn-primary(type='submit') Delete