Is there a way to convert a date value to a User's timezone in Mongoose?

Viewed 96

I have searched everywhere, StackOverflow and else where but I can't seem to find a fix for my problem. I have a mongoose schema like this:

// user.model.js
const mongoose = require('mongoose');

const User = new Schema({
  firstName: String,
  lastName: String,
  tz: String,
  registrationDate: {
    type: Date,
    default: Date.now(),
  }
})

And I have a controller which creates a User like this:

// user.controller.js (async)
let user = await User.create({
  'firstName': 'John',
  'lastName': 'Doe',
  'tz': 'Africa/Kampala'
});

await reply.send(user); // I am using Fastify framework

No matter what I do, when the User is returned it always gives the UTC time and not the time that the User actually is in. have tried using Mongoose transform:

// Transform on the schema
const moment = require('moment-timezone');

const User = new Schema({
  // Schema definitions
}, {
  toJSON: {
    transform: function (doc, ret) {
      ret.registrationDate= moment.tz(doc.registrationDate, doc.tz).format();
      return ret;
    }
  }
})

And have also tried using get like this:

const User = new Schema({
  // Other definitions
  registrationDate: {
    type: Date,
    default: Date.now(),
    get: convertDate
  }
})

function convertDate(registrationDate) {
  return moment.tz(registrationDate, this.tz).format()
}

But no luck. I would appreciate any assistance or guidance in getting this to work on the model. Thanks!

0 Answers
Related