Home > Net >  NestJS, Mongoose - timestamps returning milliseconds instead of seconds
NestJS, Mongoose - timestamps returning milliseconds instead of seconds

Time:12-03

Above the schema I have the following decorator

@Schema({
  discriminatorKey: 'kind',
  timestamps: {
    currentTime: () => Math.floor(Date.now() / 1000),
    createdAt: 'CreatedAt',
    updatedAt: 'UpdatedAt',
  },
})

And in the schema, I have

@Prop()
CreatedAt: number;

@Prop()
UpdatedAt: number;

Whenever I update some field, the UpdatedAt value is in millisecond instead of second as defined in timestamps.currentTime, 1638265771286 instead of 1638265771. How can I fix this? Thanks.

CodePudding user response:

It turns out I'm using bulkWrite which doesn't trigger pre-hook for timestamps and completely ignores the function provided in currentTime. It uses an ISO Date object then casts the object to number which returns timestamp in ms instead of second. Manually setting UpdatedAt to second in the update keys seems not to work.

  • Related