Frosty CMS: Adding Date To Posts πŸ“†

Add Date to Schema

Continuing our series on Frosty CMS, where we are building a blog CMS from scratch. Now let’s add a date to our posts that will show when they were created. We’ll start by adding date to our Mongoose post schema:

// Mongoose Schema for Posts
var postSchema = new mongoose.Schema({
    image: String,
    title: String,
    author: String,
    date: {type:Date, default: Date.now},
    short: String,
    content: String
});

Note that we have also given a default value if the date is not entered manually. This can be done with other values in the Schema.

Add Date To New Post Form

We need a way to input the date into the database so we add it to our new post form:

<div class="form-group">
    <label for="dateInput">
        <h4>Date</h4>
    </label>
    <input type="date" class="form-control" id="dateInput" name="date">
    <small id="dateInputHelp" class="form-text text-muted">If left blank will default to current date.</small>
</div>

Display Date

I’m choosing to only display the date on the single post page. So we will add that to the singlePost.ejs template.

<!-- begin content -->
<!-- fixed width container for content -->
    <div class="container-lg mt-5">

        <!--Header Image -->
        <img src="<%= post.image %>" class="img-fluid" >
        <!--Title & Author -->
        <h1><%= post.title %></h1>
        <h6><%= post.author %></h6>
        <h6><%= post.date %></h6>

        <!--Content -->
        <p class="font-weight-normal mt-5"><%= post.content %></p>

    </div>

Add Date to Route

And lastly we need to add the date to our POST route so that we can capture the data from the form when we submit it.

//----------------------------
// .POST routes
//----------------------------

app.post("/posts", function(req, res){
    // get data from form and add to posts array
    var title = req.body.title;
    var author = req.body.author;
    var date = req.body.date;
    var content = req.body.content;
    var short = req.body.short;
    var image = req.body.image;
    
    var newPostFormData = {title: title, author: author, date: date, content: content, image: image, short: short};

.toDateString()

There is a JavaScript method that we can use to make the date more legible:

<h6><%= blog.date.toDateString() %></h6>

GitHub Repo

Ncoughlin: Frosty