How to add a timestamp field into a Mongoose schema?

Sometimes, we want to add a timestamp field into a Mongoose schema.

In this article, we’ll look at how to add a timestamp field into a Mongoose schema.

How to add a timestamp field into a Mongoose schema?

To add a timestamp field into a Mongoose schema, we can use set the timestamps option when we create the schema.

For instance, we write

const mongoose = require('mongoose');
const {
  Schema
} = mongoose;

const schemaOptions = {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  },
};

const mySchema = new Schema({
  name: String
}, schemaOptions);

to create the mySchema schema with the Schema constructor.

We pass in schemaOptions as the 2nd argument, which has the timestamps option.

We set the createdAt and updatedAt properties to the field names of the created at and updated at timestamp fields.

Conclusion

To add a timestamp field into a Mongoose schema, we can use set the timestamps option when we create the schema.