'MongoError: can't convert from BSON type string to Date
I am using node js API that selects a date from mongoDb. I have a field in mongodb which stores datetime value
{
conDate : "2020-12-09 00:00:00"
}
I want to convert this to 12/09/2020 (m/d/Y format). I have tried the following code
this.gameModel.aggregate(
[
{
$project: {
monthDayYear: { $dateToString: { format: "%m/%d/%Y", date: "$conDate" } },
}
}
]
)
But this results in following error
MongoError: can't convert from BSON type string to Date
How can I convert the datetime to required format in node js.
Solution 1:[1]
You should never store date/time values as strings, use proper Date object.
Convert the string to Date, then you can extract
monthDayYear: { $dateToString: { format: "%m/%d/%Y",
date: { $dateFromString: { dateString: "$conDate", format: "%Y-%m-%d %H:%M:%S"} } }
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
