在过去的两个小时里,我一直在抓狂,起初我以为 Moment.js 是没有返回正确时间的罪魁祸首,但其实是 mongoose Date.now 做了一些邪恶的事情。
这是代码
const moment = require('moment');
const mongoose = require('mongoose');
const item = new mongoose.Schema({
time: { type: Date, default: Date.now },
time2: { type: Date }
});
正如你所看到的,我有两个字段,一个用于猫鼬的默认日期,另一个只是用于存储日期的字段。
item.pre('save', function() {
console.log(moment()); // Showing a correct date and time
console.log(this.time); // Showing a correct date but false time
this.time2 = moment(); // When it is saved to the database, it will show a correct date but false time
});
结果是
moment("2017-01-09T19:42:48.896") // the first console.log. This is correct, the time is correct
2017-01-09T11:42:48.884Z // Second console.log. The date is correct but the time is FALSE
我以为如果我这样做一切都会解决
const item = new mongoose.Schema({
time: { type: Date, default: moment() },
time2: { type: Date, default: Date.now }
});
但你知道第一个字段的 console.log 是什么time
?
2017-01-09T11:42:48.884Z // it is this time which is WRONG TIME
我的猜测是猫鼬数据类型(日期)的时区检查不准确。
任何帮助,将不胜感激。