in

Frosty CMS: Display Comments ✏️

Frosty CMS Logo

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.

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).

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>
<% }); %> 

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.

GitHub Repo

Dark Mode

frosty (this link opens in a new window) by ncoughlin (this link opens in a new window)

Frosty is a simple Javascript only blog CMS built with Node, Express and Mongo

Javascript logo

JavaScript: Async Await

Frosty CMS Logo

Frosty CMS: Authentication With Passport JS ✈️