add created_at and updated_at fields to mongoose schemas

Is there a way to add created_at and updated_at fields to a mongoose schema, without having to pass them in everytime 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 }
});

22 Answers
22

Leave a Comment