Working With Dates
When you create a user document, Mongoose will cast the value to a using the Date()
constructor.
const user = new User({
name: 'Jean-Luc Picard',
lastActiveAt: '2002-12-09'
});
user.lastActiveAt instanceof Date; // true
An invalid date will lead to a CastError
when you .
const episodeSchema = new mongoose.Schema({
title: String,
airedAt: {
// Star Trek: The Next Generation
min: '1987-09-28',
max: '1994-05-23'
}
});
const Episode = mongoose.model('Episode', episodeSchema);
const ok = new Episode({
title: 'Encounter at Farpoint',
airedAt: '1987-09-28'
});
ok.validateSync(); // No error
airedAt: '1999-06-02'
});
bad.airedAt; // "1999-06-02T00:00:00.000Z"
// Path `airedAt` (Tue Jun 01 1999 20:00:00 GMT-0400 (EDT)) is after
// maximum allowed value (Sun May 22 1994 20:00:00 GMT-0400 (EDT)).
bad.validateSync();
MongoDB supports querying by date ranges and sorting by dates. Here’s some examples of querying by dates, date ranges, and sorting by date:
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 to dates automatically.
const moment = require('moment');
const user = new User({
name: 'Jean-Luc Picard',
lastActiveAt: moment.utc('2002-12-09')
});
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.
, which means that Mongoose does not store timezone information by default. When you call Date#toString()
, the JavaScript runtime will use your OS’ timezone.