DEV Community

Cover image for Mongoose auto timestamp
Ravi Agheda
Ravi Agheda

Posted on

7

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay