Mongoose Date.now time is not accurate

2020-05-01 17:27发布

问题:

I've been tearing my hair out for the past 2 hours, At first I thought Moment.js is the culprit for not returning a correct time, but it was mongoose Date.now that has been doing some evil stuff.

Here's the code

const moment = require('moment');
const mongoose = require('mongoose');

const item = new mongoose.Schema({
   time: { type: Date, default: Date.now },
   time2: { type: Date }
});

As you can see I have two fields, one is for the default date from mongoose and the other one is just a field for storing 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

});

The result is

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

I thought If I do this everything will be solved

const item = new mongoose.Schema({
       time: { type: Date, default: moment() },
       time2: { type: Date, default: Date.now }
 });

But you know what is the console.log for the first field which is time?

2017-01-09T11:42:48.884Z // it is this time which is WRONG TIME

My guess would be that mongoose data type which is Date has an inaccurate timezone check.

Any help would be appreciated.

回答1:

You are comparing two different things. moment() gives time in local time zone and Date.now is time in UTC. The only reason mongoose has that way is because mongo db saves it that way. No fix is required here.

Just convert the fetched mongoose date back to local time zone using moment library.