简体   繁体   English

mongoose 中的日期?

[英]Dates in mongoose?

I know that I can set Date.now as a default value in a mongoose schema, but what other Javascript date types or are all dates automatically converted to mongodb´s standard format - ISOdate ?我知道我可以将Date.now设置为mongoose架构中的默认值,但是还有哪些其他 Javascript 日期类型或所有日期都自动转换为 mongodb 的标准格式 - ISOdate

Are there anything I should be concerned about when it comes to storing dates?在存储日期方面有什么我应该关心的吗?

dates: {
    created:  {type: Date, default: Date.now},
}

Thanks谢谢

The only thing you should take care of is converting the MongoDB/BSON UTC date to your local timezone (in case you need this). 您唯一需要注意的是将MongoDB / BSON UTC日期转换为您当地的时区(如果您需要)。

For more info checkout: http://docs.mongodb.org/manual/reference/bson-types/#document-bson-type-date 有关更多信息,请访问: http//docs.mongodb.org/manual/reference/bson-types/#document-bson-type-date

Mongoose date casting has a couple of small cases where it differs from JavaScript's native date parsing. Mongoose 日期转换有几个小案例,它不同于 JavaScript 的本机日期解析。
You might be interested in reading how to work with dates, to better understand casting errors and common pitfalls: https://mongoosejs.com/docs/tutorials/dates.html .您可能有兴趣阅读如何使用日期,以更好地理解转换错误和常见陷阱: https://mongoosejs.com/docs/tutorials/dates.html

  1. Mongoose looks for a valueOf() function on the given object, and calls valueOf() before casting the date. Mongoose 在给定的 object 上查找 valueOf() function,并在转换日期之前调用 valueOf()。 This means Mongoose can cast moment objects to dates automatically.这意味着 Mongoose 可以自动将时刻对象转换为日期。
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"
  1. By default, if you pass a numeric string to the Date constructor, JavaScript will attempt to convert it to a year.默认情况下,如果将数字字符串传递给 Date 构造函数,JavaScript 将尝试将其转换为年份。

    new Date(1552261496289); // "2019-03-10T23:44:56.289Z"
    new Date('1552261496289'); // "Invalid Date"
    new Date('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. Mongoose 转换包含 JavaScript 中可表示日期范围之外的数字的数字字符串,并将它们转换为数字,然后再将它们传递给日期构造函数。

你需要覆盖到new Date(req.body.time).toString() ,req.body.time是一个时间格式月/日/年或月 - 日 - 月前一天

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM