Search code examples
javascriptmongoosemongoose-schema

mongoose schema default property is not updating


I'm saving timeStamp when mongoose created document.

My problem is that timeStamp is not changing properly. Whenever I save the document, createdAt returns the moment when server has started.

mongoose model to save timeStamp (using createdAt property)

import { Schema, model } from 'mongoose';
import moment from 'moment-timezone';

const requestSchema = new Schema({
  createdAt: {
    type: String,
    default: moment
      .tz(new Date(), 'Asia/Seoul')
      .format('YYYY-MM-DD HH:mm:ss'),
  },
  ...
})

And I'm creating mongodb document in function like below

export const returnRecordObject = async (arg) => {
  const recordObject = { type: 'record' }
  const savedRecord = await models.Request.create(recordObject);
  if(savedRecord) {
    return savedRecord;
  } else {
    ...
  }
}

It seems that new Date() is not called at every create call of mongoose. I'm not that familiar to mongoose, so I couldn't find any APIs.

To summarize,

1) How can I make mongoose's default to be updated on every create or other function call?

2) Would it be better to explicitly assign createdAt property before create of mongoose? For example, code like below is better than above?

import { Schema, model } from 'mongoose';

const requestSchema = new Schema({
  // Remove createdAt property
  ...
})
export const returnRecordObject = async (arg) => {
  const recordObject = { type: 'record', createdAt: moment
      .tz(new Date(), 'Asia/Seoul')
      .format('YYYY-MM-DD HH:mm:ss')}
  const savedRecord = await models.Request.create(recordObject);
  if(savedRecord) {
    return savedRecord;
  } else {
    ...
  }
}

Solution

  • You passed a value to default that mean the default is value of moment.tz(new Date(), 'Asia/Seoul').format('YYYY-MM-DD HH:mm:ss') when this line of code run. To make it work as you expected, you need to pass in a function that return moment.tz(new Date(), 'Asia/Seoul').format('YYYY-MM-DD HH:mm:ss'). Something like:

    default: function() {
      return moment.tz(new Date(), 'Asia/Seoul').format('YYYY-MM-DD HH:mm:ss')
    }...
    

    You can read more: here