node.js - 尝试从 mongodb 格式化 DATE 时出现问题

标签 node.js mongodb express mongoose

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

// 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 }}

不过,每当我加载包含此元素的 View 时,都会收到 500 错误:

Cannot call method 'toDateString' of undefined

EDIT1:我在 View 中嵌入 {{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

最佳答案

我重写了这个,以清楚地表明您的约会内容失败的地方:

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;
};

另外,如果这对您不起作用,我推荐图书馆 moment ,这比原生 Javascript 日期更容易使用。

关于node.js - 尝试从 mongodb 格式化 DATE 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914604/

相关文章:

mongodb - 使用 MongoDB 和 Golang 没有解码器错误

javascript - Node JS : How to get the server's port?

Node.js 事件驱动范式 = 乱码?

javascript - setTimeout 与 mongodb 每个

java - 如何使用存储库模式更新 mongodb 中的嵌入文档

node.js - CASL能力科目助手有条件

javascript - 修改req.body和res。 Node.Js/Express 应用程序中的参数

javascript - Meteor:在渲染的回调中访问上下文(模板)数据

node.js - 当机器人识别器向 Luis 模型发出异步请求时,如何使用 botframework 的 sendTyping()?

c - 哪个 NoSQL 数据库与 C 一起使用?