0 votes
1 view
in SQL by (28.1k points)

Is there a way to add created_at and updated_at fields to a mongoose schema, without having to pass them in every time new MyModel() is called?

The created_at field would be a date and only added when a document is created. The updated_at field would be updated with new date whenever save() is called on a document.

I have tried this in my schema, but the field does not show up unless I explicitly add it:

var ItemSchema = new Schema({ 

name : { type: String, required: true, trim: true } 

, created_at : { type: Date, required: true, default: Date.now }


1 Answer

0 votes
by (68.3k points)

If you want to add created_at and updated_at fields to mongoose schemas use update() or findOneAndUpdate()with {upsert: true} option you can use $setOnInsert:-

var update = { 

updatedAt: new Date(), 

$setOnInsert: { 

  createdAt: new Date() 


Welcome to Intellipaat Community. Get your technical queries answered by top developers !