0

I have a timezone problem when I try to store something in mongodb using mongoose.

I created a schema like this:

var userSchema = new mongoose.Schema({
    name: {
        type: String
    },
    created_at: {
        type: Date
    }
});

It is important in my code to find users in a date range ($gte and $lte).

The problem occurs when create users:

user.created_at = new Date();

In my database this user is created with a wrong timezone.

I had tried to use "moment-timezone.js" like:

user.created_at = moment().tz("America/Belem").format();

The problem with timezone still the same in mongodb, but when I console log "moment().tz("America/Belem").format()" I got the right timezone just in database it goes wrong, so I think the problem is with type Date in mongoose, because it saving in UTC time, but I want in local time.

I have tried to use type String instead of type Date in my schema and I got the right timezone with "moment-timezone.js", but my query for $gte and $lte to find the users didn't work anymore.

In this discussion here the problem is the same, but they say about change the server timezone to UTC, but they don't show how to do it. I tried this to change the server timezone but it doesn't work for me (I'm using windows 10) and I think it is not the right path.

Please help me with this issue. Show me the best way to solve this problem.

Thank you.

Community
  • 1
  • 1
Pedro Ramos
  • 105
  • 8

1 Answers1

0

You can do like this:

var d = new Date();
d.setUTCHours(0, 0, 0, 0); // hour,minute,seconds,milliseconds
user.created_at=d;

By this way you can set UTChours for "America/Belem".

For example America/Belem has UTC hours +5 then u can do

d.setUTCHours(5, 0, 0, 0); 
Simran
  • 2,364
  • 1
  • 12
  • 19