YelpCamp Refactor

 

by Ian Schoonover

Moment JS

Time passed since date created

We'll be adding a "time since.." feature to our application, using Moment JS

I'll be working from the YelpCamp > Final version which can be found here 

Overview

  • Install moment js
  • Require moment and add it to app.locals
  • Update campground and comment models
  • Use moment in your show.ejs file

Install Moment JS

Open your command line (terminal) and install moment js to your project with the following command:

npm i -S moment

*If you're not familiar with the above syntax, it is simply shorthand for:

npm install --save moment

Require Moment and add it to app.locals

Open app.js and add the following code right above your passport configuration code:

app.locals.moment = require('moment');

*Now moment is available for use in all of your view files via the variable named moment

Update Campground and Comment Models​

  • Open /models/campground.js
  • Add createdAt: { type: Date, default: Date.now }, to the campgroundSchema:
var mongoose = require("mongoose");

var campgroundSchema = new mongoose.Schema({
   name: String,
   image: String,
   description: String,
   cost: Number,
   location: String,
   lat: Number,
   lng: Number,
   createdAt: { type: Date, default: Date.now },
   author: {
      id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"
      },
      username: String
   },
   comments: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }
   ]
});

module.exports = mongoose.model("Campground", campgroundSchema);

Update Campground and Comment Models​

  • Open /models/comment.js
  • Add createdAt: { type: Date, default: Date.now }, to the commentSchema:
var mongoose = require("mongoose");

var commentSchema = mongoose.Schema({
    text: String,
    createdAt: { type: Date, default: Date.now },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

module.exports = mongoose.model("Comment", commentSchema);

Use Moment in Your show.ejs File

  • Open /views/campgrounds/show.ejs
  • Change the following lines from this:
<p>
    <em>Submitted By <%= campground.author.username %></em>
</p>
<p>
  <em>Submitted by: <%= campground.author.username %>, <%= moment(campground.createdAt).fromNow() %></em>
</p>
  • to this:
<span class="pull-right">10 days ago</span>
<span class="pull-right"><%= moment(comment.createdAt).fromNow() %></span>
  • to this:
  • and from this:

Congratulations! Your YelpCamp app now has "time since created" functionality

If you have any questions then please create a thread in the Q&A

YelpCamp Refactor - Moment JS

By nax3t

YelpCamp Refactor - Moment JS

Refactoring of YelpCamp from The Web Developer Bootcamp

  • 16,192