Displaying Dates from MongoDB with Express.js [closed]-Collection of common programming errors

I saved few datasets to MongoDB using mongoose.js. But I got a problem with displaying them on an html site using express.js and ejs.

Here is my scenario:

Model

var mongoose = require('mongoose');

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var ItemSchema = new Schema({
    _id: ObjectId,
    creationTime: Date,
    modificationTime: Date,
    title: String
});
var Item = mongoose.model('item', ItemSchema);
module.exports.Item = Item;

Route:

app.get('/item/:id', function(req, res) {

    Item.findById(req.params.id, function(err, doc){

        console.log(doc); //This check displays everything correctly on console

        res.render('item.html.ejs', {
            item : doc
        });
    });
});

View:

:


Creation:
Modification:

The result of this setting is that title is being displayed correctly while both dates are undefined.

I assume it has something to do with MongoDB’s ISODate format. But I can’t find a solution on how to convert it for displaying in html views.

I appreciate your help. Cheers

  1. If you just copied and pasted the code the solution is very very simple.

    In your model you defined creationTime and modificationTime in your template you try to access item.creationDate and item.modificationDate.

    After that change you should be able to see something other then undefined, but you probably still need to convert this into a proper date format.

  2. I have the following helpers using moment.js in my projects.

    date: function(date){
      moment(date).format('YYYY-MM-DD hh:mm:ss');
    },
    fromNow: function(date){
      moment(date).fromNow()
    }
    
  3. I add an ejs filter using the example above, but I had to change it a little bit to get it to work:

    Create the ‘created_at’ attribute on the mongoose schema and automatically create it on save():

    var ItemSchema = new Schema({
        name    : { type: String, required: true, trim: true }
      , created_at    : { type: Date }
    });
    
    
    ItemSchema.pre('save', function(next){
      if ( !this.created_at ) {
        this.created_at = new Date;
      }
      next();
    });
    

    Install moment (and write to package.json)

    npm install moment --save
    

    Add the filter in app.js or wherever else you define filters for ejs:

    var moment = require('moment');
    
    ejs.filters.fromNow = function(date){
      return moment(date).fromNow()
    }
    

    Use the filter in page.ejs

    
    

Originally posted 2013-11-09 22:59:29.