Anthony Mayfield Anthony Mayfield - 1 month ago 11
Node.js Question

How to store mongoose value as a date?

Everytime I save a date in Mongoose it ends up as a string.

let newDate = new Date().toISOString();

let thing = await Thing.findOne({});

things.details.expirationDate = newDate;

await thing.save();


I can confirm that in the database it is recognized as a string and not a date object.

How do I save this value on a date object?
thing.details
is a mixed schema type.

Answer

The method .toISOString() creates a string from the given date in the format

2016-10-05T14:48:00.000

and then that string is stored in the database, not an object

To store a date object, you can simply do

let newDate = new Date();

and Moongose should do the type conversion between javascripts Date object and the ISODate generally used by MongoDB.