Working With Dates

    When you create a user document, Mongoose will cast the value to a using the Date() constructor.

    1. const user = new User({
    2. name: 'Jean-Luc Picard',
    3. lastActiveAt: '2002-12-09'
    4. });
    5. user.lastActiveAt instanceof Date; // true

    An invalid date will lead to a CastError when you .

    1. const episodeSchema = new mongoose.Schema({
    2. title: String,
    3. airedAt: {
    4. // Star Trek: The Next Generation
    5. min: '1987-09-28',
    6. max: '1994-05-23'
    7. }
    8. });
    9. const Episode = mongoose.model('Episode', episodeSchema);
    10. const ok = new Episode({
    11. title: 'Encounter at Farpoint',
    12. airedAt: '1987-09-28'
    13. });
    14. ok.validateSync(); // No error
    15. airedAt: '1999-06-02'
    16. });
    17. bad.airedAt; // "1999-06-02T00:00:00.000Z"
    18. // Path `airedAt` (Tue Jun 01 1999 20:00:00 GMT-0400 (EDT)) is after
    19. // maximum allowed value (Sun May 22 1994 20:00:00 GMT-0400 (EDT)).
    20. 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.

    1. const moment = require('moment');
    2. const user = new User({
    3. name: 'Jean-Luc Picard',
    4. lastActiveAt: moment.utc('2002-12-09')
    5. });

    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.