尝试从mongodb格式化date时出现问题

我正在尝试在显示模型之前在模型上格式化datetypes属性。 这是我正在使用的代码:

// 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); 

而在客户端,我尝试显示格式化date使用:

 {{ article.dateString }} 

不过,每当我加载包含这个元素的视图,我得到一个500错误:

 Cannot call method 'toDateString' of undefined 

EDIT1:我没有在我的视图embedded{{article.snapshot}}的问题,但是当涉及到Date对象,我得到一个错误

编辑2:使用console.log(article.dateString())loggingdateString方法时,我得到以下内容:

 Wed Sep 18 2013 

编辑3:这是当我使用由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 

我已经重写了这一点,以清楚你的date的东西是失败的:

 ArticleSchema.methods.dateString = console.log('this.PostDate: ' + this.postDate) var parsed = Date.parse(this.postDate) console.log('parsed: ' + parsed) var date = new Date(parsed); console.log('date: ' + date) var toString = date.toDateString(); comsole.log('toString: ' + toString) return toString; }; 

另外,如果这不适合你,我build议图书馆的时刻 ,这比本地JavaScriptdate更容易处理。