Check out bidbear.io Amazon Advertising for Humans. Now publicly available 🚀

Frosty CMS: Display Comments ✏️

Intro

Continuing our series on Frosty CMS, where we are building a blog CMS from scratch. Just previously we worked on seeding the database with some blog posts and comments. Now we need to display those comments on our single post template.

Updating The Route

Here is our route as it currently stands.

// render individual post. This is a wildcard link and must therefore be
// placed after static links in the application!
app.get("/blogs/:id", function(req, res){
    // find post with provided ID
    Blog.findById(req.params.id, function(err, dbData){
        if(err){
            console.log("error finding blog data by ID");
        } else {
            console.log(dbData);
            // render single post template with that post data
            res.render("singleBlog.ejs", {blog: dbData});
        }
    });
});

And because we are logging the dbData in the response we should see what we get back in the console when we request this page.

comment id in console

And note that we are getting our comment, but it is just a comment ID. We need to actually populate the comment. So lets update our route to do that now.

// render individual post. This is a wildcard link and must therefore be
// placed after static links in the application!
app.get("/blogs/:id", function(req, res){
    // find post with provided ID
    Blog.findById(req.params.id).
    // populate comments
    populate("comments").
    exec(function(err, dbData){
        if(err){
            console.log("error finding blog data by ID");
        } else {
            console.log(dbData);
            // render single post template with that post data
            res.render("singleBlog.ejs", {blog: dbData});
        }
    });
});

and now if we request that post again we will be requesting the actual content of the comment (we have populated the content from another collection).

comment in console

Nothing will be displayed on the page of course because we haven’t actually updated our single blog display template to display this information yet. Let’s work on that now.

Display Comment in Template

This is the easy part. We simply need to add a loop into the singleBlog.ejs template.

<!--Comments Loop -->
<% blog.comments.forEach((comment) => { %>
    <p><strong><%= comment.author %></strong></p>
    <p><%= comment.content %></p>
<% }); %>

comment on page

Styling the Single Post Page

We have basically no styling on this page, so lets go ahead and give it a facelift so it looks decent.

comment collapse

GitHub Repo

Ncoughlin: Frosty

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart