【问题标题】:Mongoose Date Schema猫鼬日期模式
【发布时间】:2018-10-18 14:39:41
【问题描述】:

我正在使用 MongoDB、Mongoose、Express 和 Express Handlebars。

我的表单中有一个<input type="date">,它发布到数据库,我的猫鼬模式定义如下:

var recordsSchema = new mongoose.Schema ({
   scheduled: Date,
});

表单插入时间,但输出看起来像这样:

2018 年 10 月 26 日星期五 00:00:00 GMT+0000 (UTC)

我想对其进行格式化,使其显示为:

2018 年 10 月 26 日星期五

并且没有其他任何东西。

我尝试在 Handlebars 模板中使用 toString() 方法,但它不起作用并且服务器抛出错误。

这是它在 Express-Handlebars 一侧的外观:

{{ this.scheduled }} {{ this.scheduled.toString() }}

谁能告诉我如何解决这个问题?

谢谢。

【问题讨论】:

  • 你试过.toDateString()吗?并且您可以在架构中使用自定义 getter 来获取所需的格式。
  • 嗨 Shiv,是的,我尝试了 toDateString() 但这也不起作用。我应该如何更改架构?
  • 我认为您已经从日期对象中获取子字符串,例如:Date().substr(0,15)

标签: node.js mongodb mongoose express-handlebars


【解决方案1】:

尝试在架构中添加自定义 getter 以按预期获取格式化的日期字符串。

var recordsSchema = new Schema ({
  scheduled: Date,
  get: value => value.toDateString()
});

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 2020-04-12
    • 2020-05-03
    • 2012-02-17
    • 2020-06-11
    • 2020-02-10
    • 2016-08-05
    • 2018-07-05
    • 2016-10-01
    相关资源
    最近更新 更多