Persisting time with timezone offset in mongodb with nestjs

Viewed 588

I have a nestjs application which has a very date heavy schema. According to my understanding date is stored in mongo without timezone. My API accepts time in ISO format with timezone offset.

Inserting following object {"date": "2009-06-30T18:30:00+11:00"}

will result in following document in the mongo database {date: ISODate('2009-06-30T07:30:00.000Z'), _id: "..."}

So the timezone offset is lost.

Is there an elegant way to keep the timezone offset and deliver the ISO string with the same offset on an GET request? Maybe make use of the class-transformer and store the offset in a separate property? If yes, how?

Here are the involved classes. (There is a dedicated ItemDto for GET requests which is not shown here.)

Dto:

export class CreateItemDto {

  // Some other props are here

  /**
   * Date of this Information.
   * @example "1900-01-01T05:00:00.000+05:00"
   */
  @IsNotEmpty()
  @IsDate()
  @Type(() => Date)
  date: Date;
}

Schema:

export class ItemSchema {

  // Some other props are here

  @Prop({ type: Date, required: true })
  date!: Date;
}
1 Answers

In many cases the client application will convert and display the time in current local time zone, no matter in which time zone the timestamp was inserted.

If this is not sufficient for you then you have to store the time zone information in a separate field along with the actual timestamp.

Related