it insert into database in this format 2021-08-06T00:00:00.000+00:00
Actually a document like {_id:ObjectId(), dt: Date("2021-08-06")
is inserted into the database in this format (see bsonspec.org):
00000000: 2200 0000 075f 6964 0061 0dd3 1dfd af14 "...._id.a......
00000010: db18 d4f9 6109 6474 0000 6cc2 187b 0100 ....a.dt..l..{..
00000020: 0000
The date value there is the 64-bit integer:
hex: 0x000017b18c26c00
decimal: 1628208000000
That is also the format that is returned by the MongoDB server to whatever client program you are using.
The Node.js driver recognizes that is a date type, and so helpfully deserializes that value using the Date
constructor, such as:
new Date(1628208000000)
Try that from a REPL, and you will see that it is actually Node that is providing the format that you see:
From the mongo shell, that looks like:
> new Date(1628208000000)
ISODate("2021-08-06T00:00:00Z")
JSON doesn't have a date type, so converting will result in that value becoming string:
> tostrictjson({dt:new Date(1628208000000)})
{ "dt" : { "$date" : "2021-08-06T00:00:00.000-00:00" } }
Again, that is the client, not the database, producing the format that you see.
If you need to display the date in a particular format, use a date formatting library like Datejs, Moment.js, Luxon, etc.