Automatically set mongoose schema properties on save or update Automatically set mongoose schema properties on save or update mongoose mongoose

Automatically set mongoose schema properties on save or update


You can add timestamps to your schema and it will automatically create createdAt and updatedAt fields, updatedAt will get updated every time you update the document

export const UserSchema = new Schema<IUser>({/* schema */}, { timestamps: true })

You can also rename the fields like this

{ timestamps: { createdAt: 'createdOn', updatedAt: 'updatedOn' }}


Use 'default' in your Schema (https://mongoosejs.com/docs/defaults.html). This will set the current date on creation.

 createdOn: {  required: true,  type: Date,  set: Date.now,  default: Date.now},updatedOn: {  required: true,  type: Date,  default: Date.now}

As for to update the timestamp on a .update - If you are running mongoose >4.0, you can use timestamps

https://mongoosejs.com/docs/guide.html#timestamps