【问题标题】:How to change Date format in MongoDB and mongoose [duplicate]如何在 MongoDB 和 mongoose 中更改日期格式 [重复]
【发布时间】:2019-03-01 19:12:12
【问题描述】:

我有以下代码。

const Price = mongoose.model('Price', new mongoose.Schema({
  dateFrom: {
    type: Date,
    required: true
  },
  dateTo: {
    type: Date,
    required: true
  }
}));

在数据库中,它们以格式存储,即 2018-12-29T00:00:00.000Z。 我想做的是将存储为 2018-12-29。有没有办法做到这一点?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您可以通过这种方式操作发送的值。我希望它有效

    function formatDate(date) {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();
    
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
    
        return [year, month, day].join('-');
    }
    
    
    const Price = mongoose.model('Price', new mongoose.Schema({
        dateFrom: {
          type: String,
          required: true,
          set: date => formatDate(date)
        },
        dateTo: {
          type: String,
          required: true,
          set: date => formatDate(date)
        }
    }));
    

    【讨论】:

    • 我仍然得到 2018-12-29T00:00:00.000Z 格式..
    • 您可以通过将其替换为'String'来更改类型值
    • @Minan 不要将日期存储为“字符串”。即使作为 YYYYMMDD 的“字符串”,它仍然比 BSON 日期的内部 64 位整数格式多字节存储。
    • @Neil Lunn 是的,你完全正确。但是还有其他方法可以这样记录吗?也许只有在被请求时才更正它会更正确。 'get' 方法可用于此
    • 现有答案中涵盖了“任何其他方式”,这些答案已经存在了很长时间,并且该问题已被标记为重复。我建议你自己也看看。
    猜你喜欢
    • 2019-06-25
    • 2011-12-27
    • 2011-12-23
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2023-01-25
    相关资源
    最近更新 更多