Search code examples
node.jsmongodbmongoosemongoose-schema

Storing time using default in mongoose schema , saves the same time again and again


I have a mongoose schema which includes:

dateTime: {
    type: Date,
    default: moment().tz("Asia/Karachi").format(),
},

But when I am saving records in MongoDB its storing the same time again and again.

Record One saved: enter image description here

Record Two saved:

enter image description here


Solution

  • By specifing a default value this exact value will be used for all the records. You probably want to define a default function instead:

    dateTime: {
        type: Date,
        default: () => moment().tz("Asia/Karachi").format()
    },