使用日期
¥Working With Dates
以下是如何使用 Mongoose 结构声明 Date
类型的路径:
¥Here's how you declare a path of type Date
with a Mongoose schema:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
// `lastActiveAt` is a date
lastActiveAt: Date
});
const User = mongoose.model('User', userSchema);
当你创建用户 document 时,Mongoose 会使用 Date()
构造函数 将值转换为 原生 JavaScript 日期。
¥When you create a user document, Mongoose will cast
the value to a native JavaScript date
using the Date()
constructor.
const user = new User({
name: 'Jean-Luc Picard',
lastActiveAt: '2002-12-09'
});
user.lastActiveAt instanceof Date; // true
当你 验证文档 时,无效日期将导致 CastError
。
¥An invalid date will lead to a CastError
when you validate the document.
const user = new User({
name: 'Jean-Luc Picard',
lastActiveAt: 'not a date'
});
user.lastActiveAt instanceof Date; // false
user.validateSync().errors['lastActiveAt']; // CastError
验证器
¥Validators
日期有两个内置验证器:min
和 max
。如果给定日期严格小于 min
或严格大于 max
,这些验证器将报告 ValidatorError
。
¥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
.
const episodeSchema = new mongoose.Schema({
title: String,
airedAt: {
type: Date,
// The dates of the first and last episodes of
// 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
const bad = new Episode({
title: 'What You Leave Behind',
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();
查询
¥Querying
MongoDB 支持按日期范围查询和按日期排序。以下是按日期、日期范围查询和按日期排序的一些示例:
¥MongoDB supports querying by date ranges and sorting by dates. Here's some examples of querying by dates, date ranges, and sorting by date:
// Find episodes that aired on this exact date
return Episode.find({ airedAt: new Date('1987-10-26') }).
then(episodes => {
episodes[0].title; // "Where No One Has Gone Before"
// Find episodes within a range of dates, sorted by date ascending
return Episode.
find({ airedAt: { $gte: '1987-10-19', $lte: '1987-10-26' } }).
sort({ airedAt: 1 });
}).
then(episodes => {
episodes[0].title; // "The Last Outpost"
episodes[1].title; // "Where No One Has Gone Before"
});
铸造边缘案例
¥Casting Edge Cases
日期转换有一些与 JavaScript 原生日期解析不同的小情况。首先,Mongoose 在给定对象上查找 valueOf()
功能,并在转换日期之前调用 valueOf()
。这意味着 Mongoose 可以自动将 矩对象 转换为日期。
¥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.
const moment = require('moment');
const user = new User({
name: 'Jean-Luc Picard',
lastActiveAt: moment.utc('2002-12-09')
});
user.lastActiveAt; // "2002-12-09T00:00:00.000Z"
默认情况下,如果将数字字符串传递给 Date 构造函数,JavaScript 将尝试将其转换为年份。
¥By default, if you pass a numeric string to the Date constructor, JavaScript will attempt to convert it to a year.
new Date(1552261496289); // "2019-03-10T23:44:56.289Z"
new Date('1552261496289'); // "Invalid Date"
new Date('2010'); // 2010-01-01T00:00:00.000Z
Mongoose 转换包含 JavaScript 中可表示日期的范围 之外的数字的数字字符串,并将其转换为数字,然后将其传递给日期构造函数。
¥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]
时区
¥Timezones
MongoDB 将日期存储为 64 位整数,表示 Mongoose 默认不存储时区信息。当你调用 Date#toString()
时,JavaScript 运行时将使用 你操作系统的时区。
¥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.