我正在尝试在显示模型之前格式化模型上的日期类型属性。这是我正在使用的代码:
// MODEL
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: String,
content: String,
author: { type: String, default: 'Vlad'},
postDate: { type: Date, default: Date.now }
});
ArticleSchema.methods.formatTitle = function() {
var link = this.title.replace(/\s/g, '-');
return '/article/' + link;
};
ArticleSchema.methods.snapshot = function() {
var snapshot = this.content.substring(0, 500);
return snapshot;
};
ArticleSchema.methods.dateString = function() {
var date = new Date(this.postDate);
return date.toDateString();
};
module.exports = mongoose.model('Article', ArticleSchema);
在客户端,我尝试使用以下方式显示格式化日期:
{{ article.dateString }}
尽管如此,每当我加载包含此元素的视图时,我都会收到 500 错误:
Cannot call method 'toDateString' of undefined
EDIT1:我在我的视图中嵌入 {{ article.snapshot }} 没有问题,但是当涉及到 Date 对象时,我得到一个错误
EDIT2:当使用 console.log(article.dateString()) 记录 dateString 方法时,我得到以下信息:
Wed Sep 18 2013
EDIT3:这是我在使用 dankohn 提供的代码时得到的。只是我,还是只是连续两次运行该方法?
this.postdate: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
parsed: 1379536022000
date: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
toString: Wed Sep 18 2013
Wed Sep 18 2013
this.postdate: undefined
parsed: NaN
date: Invalid Date
toString: Invalid Date