How to use Mongoose timestamps

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.