Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k 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 (106k 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() 

};

Related questions

0 votes
2 answers
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories

...