使用Express.js显示MongoDB中的日期

Sve*_*ven 3 ejs mongoose mongodb node.js express

我使用mongoose.js将少量数据集保存到MongoDB.但是我在使用express.js和ejs在html网站上显示它们时遇到了问题.

这是我的场景:

模型

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;
Run Code Online (Sandbox Code Playgroud)

路线:

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
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

视图:

<h1><%= item.title %>:</h1>
<p>Creation: <%= item.creationDate %></p>
<p>Modification: <%= item.modificationDate %></p>
Run Code Online (Sandbox Code Playgroud)

此设置的结果是两个日期都正确显示标题undefined.

我认为它与MongoDB的ISODate格式有关.但我无法找到如何转换它以在html视图中显示的解决方案.

我感谢您的帮助.干杯

Pic*_*els 9

我在我的项目中使用了moment.js以下帮助器.

date: function(date){
  moment(date).format('YYYY-MM-DD hh:mm:ss');
},
fromNow: function(date){
  moment(date).fromNow()
}
Run Code Online (Sandbox Code Playgroud)