DEV Community

Cover image for Mongoose auto timestamp
Ravi Agheda
Ravi Agheda

Posted on

Mongoose auto timestamp

Let mongoose schema handle timestamps for you

It's a little difficult to manage createdAt and updatedAt on each Create and Update operation.

We can have it handled by mongoose built-in features.There are three ways to add timestamps in mongoose schema

1. createdAt and updatedAt in timestamp format.

const mySchema = new mongoose.Schema(
    {
        name: String,
    }, 
    {
        timestamps: true,
    }
);
Enter fullscreen mode Exit fullscreen mode

output:

createdAt: 2021-02-02T06:12:26.668Z,
updatedAt: 2021-02-02T06:12:48.930Z

2. Timestamp with a custom field name

By default, the names of the fields are createdAt and updatedAt. Customize the field names by setting timestamps.createdAt and timestamps.updatedAt.

const mySchema = new mongoose.Schema(
    {
        name: String,
    }, 
    {
        timestamps: { createdAt: 'addedAt', updatedAt: 'modifiedAt' },
    }
);  
Enter fullscreen mode Exit fullscreen mode

output:

addedAt: 2021-02-02T06:12:26.668Z,
modifiedAt: 2021-02-02T06:12:48.930Z

3. Timestamp with number format (double)

By default, Mongoose uses new Date() to get the current time. If you want to overwrite the function Mongoose uses to get the current time, you can set the timestamps.currentTime option. Mongoose will call the timestamps.currentTime function whenever it needs to get the current time.

const mySchema = new mongoose.Schema(
    {
        name: String,
        createdAt: Number,
        updatedAt: Number,
    }, 
    {
        timestamps: { currentTime: ()=> Date.now() },
    }
);  
Enter fullscreen mode Exit fullscreen mode

output:

createdAt: 1612246845043,
updatedAt: 1612246853068

Top comments (0)