mongoose how to set date format in model mongoose how to set date format in model mongoose mongoose

mongoose how to set date format in model


MongoDB's underlying storage engine (BSON) does not have a type for date-without-time, just full dates (see this page for details of the BSON types in the MongoDB documentation).

The upshot of this is you will need to handle it in your code by ensuring the time is always set to (for example) 00:00:00 when inserting and querying, or by storing it as a different type (for example a yyyy-mm-dd string, or an integer). Which of these is most appropriate would depend on your requirements to query and use that date.


From the docs if in your schema you have a date type field e.g

 holidayDate: {        type: Date,    required: 'Please fill From Date'    }

and when you create your holiday document, Mongoose will cast the value to a native JavaScript date using the Date() constructor

const holiday = new Holiday({holidayDate:'2012-12-19'});holiday.holidayDate instanceof Date; // true

and an invalid date will lead to a CastError when you validate the document.

const holiday = new Holiday({holidayDate:'invalid date'});holiday.holidayDate instanceof Date; // falseholiday.validateSync().errors['lastActiveAt']; // CastError