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β
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.