【问题标题】:MongoError: can't convert from BSON type string to DateMongoError:无法从 BSON 类型字符串转换为日期
【发布时间】:2021-03-22 20:59:58
【问题描述】:

我正在使用从 mongoDb 中选择日期的节点 js API。我在 mongodb 中有一个存储日期时间值的字段

{
 conDate : "2020-12-09 00:00:00"
}

我想将其转换为 12/09/2020(m/d/Y 格式)。我试过下面的代码

this.gameModel.aggregate(
    [
      {
        $project: {
           monthDayYear: { $dateToString: { format: "%m/%d/%Y", date: "$conDate" } },
           
        }
      }
    ]
 )

但这会导致以下错误

MongoError: 无法从 BSON 类型字符串转换为日期

如何在节点 js 中将日期时间转换为所需的格式。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    您应该从不将日期/时间值存储为字符串,使用正确的 Date 对象。

    将字符串转换为Date,然后就可以解压了

    monthDayYear: { $dateToString: { format: "%m/%d/%Y", 
       date: { $dateFromString: { dateString: "$conDate", format: "%Y-%m-%d %H:%M:%S"} } } 
    },
    

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2017-06-17
      • 2017-09-23
      • 2018-05-24
      • 2018-03-20
      • 2013-01-25
      • 2015-04-09
      • 1970-01-01
      相关资源
      最近更新 更多