How can I format a date coming from MongoDB?

前端 未结 7 644
青春惊慌失措
青春惊慌失措 2021-01-30 05:19

I\'m using Jade to render my views from within Express.js. I am saving documents in MongoDB and using Mongoose to access my documents. I am saving a default date created when a

7条回答
  •  日久生厌
    2021-01-30 05:48

    I had exactly this requirements (expressjs, mongoose, jade) and this is how I solved it for myself.

    First of all I installed momentjs with npm install moment. Then I passed moment to view using this:

    var moment = require('moment');
    
    app.get('/', function(req, res){
        // find all jobs using mongoose model
        Job.find().exec(function(err, items){
            // pass moment as a variable
            res.render('status', { 'jobs': items, moment: moment });
        })
    });
    

    Then using it like this in Jade:

    table
      tr
        td Subject
        td Posted at
        td Status
      each job, i in jobs
        tr
          td #{job.subject}
          td #{moment(job.postedAt).format("YYYY-MM-DD HH:mm")}
          td #{job.status}
    

提交回复
热议问题