Mongoose schemas provide a timestamps option that configures Mongooses to automatically assign createdAt and updatedAt properties to documents.

The following example demonstrates how you can enable Mongoose built-in timestamping for the User model:

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

// Define a schema
const userSchema = new Schema(
  {
    name: String,
    age: Number
  },
  { timestamps: true }
)

// Define a model
const User = mongoose.model('User', userSchema)

// Create a document
const alex = new User({
  name: 'Alex Jones',
  age: 32
})

// Save document
await alex.save()

alex.createdAt // 2020-12-16T05:35:54.236Z
alex.updatedAt // 2020-12-16T05:35:54.236Z

alex.createdAt instanceof Date // true

Once you enable timestamps, Mongoose automatically attaches createdAt and updatedAt properties to your schema. By default, both createdAt and updatedAt properties are of type Date.

Now when you update the document, Mongoose will automatically increment the updatedAt property:

alex.age = 43
await alex.save()

alex.createdAt     // 2020-12-16T05:35:54.236Z
alex.updatedAt     // 2020-12-16T05:45:12.657Z

Alternate property names

By default, Mongoose uses createdAt and updatedAt as the field names for timestamps. But you can configure Mongoose to use alternative property names for timestamps:

// Define a schema
const userSchema = new Schema(
  {
    name: String,
    age: Number
  },
  { timestamps: { createdAt: 'created_on', updatedAt: 'updated_on' } }
)

// Define a model
const User = mongoose.model('User', userSchema)

// Create a document
const john = new User({
  name: 'John Doe',
  age: 32
})

// Save document
await john.save()

john.created_on // 2020-12-16T05:50:32.604Z
john.updated_on // 2020-12-16T05:50:32.604Z

In the above example, we customized the timestamps field names and changed them to created_on and updated_on properties instead.

UNIX timestamps

By default, Mongoose uses the Date constructor to get the current time for timestamps. However, you can configure Mongoose to store time as the number of seconds elapsed since UNIX epoch on January 1st, 1970.

For this purpose, Mongoose schemas provide the timestamps.currentTime option that lets you define a custom function to use for getting the current time:

const userSchema = new Schema(
  {
    name: String,
    age: Number
  },
  {
    // Use Unix timestamps (seconds since Jan 1st, 1970)
    timestamps: { currentTime: () => Math.floor(Date.now() / 1000) }
  }
)

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.