Here's how you declare a path of type Date
with a Mongoose schema:
constmongoose=require('mongoose');constuserSchema=newmongoose.Schema({name: String,// `lastActiveAt` is a datelastActiveAt: Date});constUser=mongoose.model('User',userSchema);
When you create a user document, Mongoose will cast the value to a native JavaScript date using the Date()
constructor.
[require:Date Tutorial.*Example 1.2]
An invalid date will lead to a CastError
when you validate the document.
[require:Date Tutorial.*Example 1.3]
Dates have two built-in validators: min
and max
. These validators will report a ValidatorError
if the given date is strictly less than min
or strictly greater than max
.
[require:Date Tutorial.*Example 1.2.1]
MongoDB supports querying by date ranges and sorting by dates. Here's some examples of querying by dates, date ranges, and sorting by date:
[require:Date Tutorial.*Example 1.3.1]
Date casting has a couple small cases where it differs from JavaScript's native date parsing. First, Mongoose looks for a valueOf()
function on the given object, and calls valueOf()
before casting the date. This means Mongoose can cast moment objects to dates automatically.
[require:Date Tutorial.*Example 1.4.1]
By default, if you pass a numeric string to the Date constructor, JavaScript will attempt to convert it to a year.
newDate(1552261496289);// "2019-03-10T23:44:56.289Z"newDate('1552261496289');// "Invalid Date"newDate('2010');// 2010-01-01T00:00:00.000Z
Mongoose converts numeric strings that contain numbers outside the range of representable dates in JavaScript and converts them to numbers before passing them to the date constructor.
[require: Date Tutorial.*Example 1.4.3]
MongoDB stores dates as 64-bit integers, which means that Mongoose does not store timezone information by default. When you call Date#toString()
, the JavaScript runtime will use your OS' timezone.