Skip to main content

Frosty CMS: Populating Template Content From the Database

Continuing our series on Frosty CMS, where we are building a blog CMS from scratch. In our last post we setup the Mongo Database. In this post we will be modifying our posts template so that it is being dynamically populated with content from the database instead of the static array we have been using as a placeholder.

This is our previous route to render the posts page. It’s telling express to the pull the data from the static array "posts". We covered that in this post.

// render the preview page
app.get("/posts", function(req, res){
res.render("posts.ejs", {posts:posts});
});

And in [Introduction to MongooseJS(/posts/introduction-to-mongoosejs/)] we covered the .find() method. As well as error/response handling for Mongoose models in our last post.

Post.create({
image: "https://ncoughlin.com/wp-content/uploads/2020/01/F4BB34AF-6E6F-4203-A1F0-321F9319A962_1_105_c.jpeg",
title: "Training Capybaras",
author: "Steve Buscemi",
content: "Always remember to bring a bag of lettuce."
}, function(err, post){
if(err){
console.log("Failed to write post to database.");
} else {
console.log("Post successfully saved to database.");
console.log(post);
}
});

And if we combine those two principles we get the following:

// render the preview page
app.get("/posts", function(req, res){
// get campgrounds from database
Post.find({}, function(err, posts){
if(err){
console.log("Error: Unable to retreive post data.");
} else {
res.render("posts.ejs", {posts:posts});
}
});
});

So here we have an express route that defines what happens when we have a GET request for the /posts page. In RESponse we are using the .find() method on our Mongoose model “Post” to pull the data associated with that schema (this is why we needed the Schema for a non-relational database).

If we get an error we get a console log, and if not, we render the posts.ejs template with the posts data. Previously posts was referencing the static array, but now we are pointing it to the Post schema data.

successfully populating our template with information from the database

GitHub Repo

Ncoughlin: Frosty

Automated Amazon Reports

Automatically download Amazon Seller and Advertising reports to a private database. View beautiful, on demand, exportable performance reports.

bidbear.io