Fair warning I am fairly new to node and may not be asking the correct questions
I am trying to make a blog on my website and would like the show route for my posts to contain a slugified version of the posts title instead of a long ID. An example is example.com/blog-title-here instead of example.com/17489349823789423832. I have installed slugify but I cannot seem to make it work. I am having trouble storing the title's as slugs and any guidance would be extremely welcome.
//SHOW BLOG ROUTE
app.get("/blogs/:slug", function(req, res){
var slug = slugify(req.body.blog.title);
Blog.find({ slug: req.params.slug}, function (err, foundBlog) {
if(err){
res.redirect("/blogs");
} else {
res.render("show", {blog: foundBlog});
}
})
});
here is the blog index page with the view post button having an href that I do not think is correct either.
<div class="blog-feed">
<div class="container">
<div class="row">
<% blogs.forEach(function(blog){ %>
<div class="col-lg-4 mb-4">
<div class="card">
<img class="card-img-top" src="<%= blog.image %>" alt="Card image cap">
<div class="card-body text-center">
<h5 class="card-title"><%= blog.title %></h5>
<p class="card-text"><%- blog.body %></p>
<a href="/blogs/<%= blog.slug %>" class="btn btn-primary">View Post</a>
</div>
</div>
</div>
<% }) %>
</div>
</div>
</div>
Here is how I save the post to the database
//CREATE BLOG ROUTE
app.post("/blogs", function(req, res){
//create blog
console.log(req.body);
req.body.blog.body = req.sanitize(req.body.blog.body)
console.log("===========");
console.log(req.body);
console.log(slugify(req.body.blog.title));
Blog.create(req.body.blog, function(err, newBlog){
if(err){
res.render("blogNew");
} else {
//then, redirect to the index
res.redirect("/blogs");
}
})
});
Thank you for your help in advance!