Open In App

Mongoose Timestamps

Last Updated : 03 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is a robust Object Data Modeling (ODM) library for Node.js and MongoDB that makes database operations easy. One of the prominent features offered by Mongoose is timestamp support. Timestamps are handled automatically by Mongoose and enable us to record the create and update times of documents within your database. This can be quite useful for a wide range of use cases including logging, versioning, or even handling time-sensitive data.

What are Mongoose Timestamps?

Mongoose timestamps are supported by the schema. Timestamps save the current time of the document created and also when it was updated in form of a Date by turning it true. When set to true, the Mongoose timestamps automatically add two fields to your document

  • createdAt: Date representing when the document was created
  • updatedAt: Date representing when this document was last updated

The two fields are created when the database was first created and then updated by the queries save(), updateOne(), updateMany(), findOneAndUpdate(), update(), replaceOne(), or bulkWrite(). Mongoose timestamps are convenient for recording document creation and modifying dates. It is very handy when you require knowing data creation or modification time for auditing, data synchronizing, or just tracking changes in the course of time.

How to Enable Timestamps in Mongoose Schema

To use timestamps in Mongoose, you just need to turn on the timestamps option in your schema definition. When you set timestamps to true, Mongoose automatically includes the createdAt and updatedAt fields in your documents. Here's the simple syntax for turning on timestamps in a Mongoose schema:

Syntax:

const studentSchema = new Schema({ name: String }, { timestamps: true });

const Student = mongoose.model('Student', studentSchema);

To learn how to efficiently manage time-based data in full-stack applications using MongoDB, the Full Stack Development with Node JS course provides hands-on examples of timestamp usage in databases

Steps to Set Up Mongoose with Timestamps

Creating Application and installing Modules: We will create a schema with the timestamps and then print the different timestamps that are createdAt and updatedAt by updating the details of a student.

Step 1: Create a folder and initialize it:

npm init

Step 2: Install mongoose in the project.

npm install mongoose

Step 3: Project Structure

 

Step 4: Create index.js File and Set Up Mongoose Connection

Create a file called index.js. Inside the index.js, connect to MongoDB. Here the MongoDB Compass is used. Now first create the Student schema and then its model. Now create a new document and save it. Print the document timestamps and then update the document after a time delay and then again print the timestamp details.

const mongoose = require("mongoose");

// Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks");

// Creating Schema
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, default: 8 },
},
{ timestamps: true }
);

// Student model
const Student = mongoose.model("Student", studentSchema);

// Creating Student document from Model

// Function to save in database
const saveStudent = async (name, age) => {
let s = new Student({
name: name,
age: age,
});
s.save().then((doc) => {
console.log("Name:", doc.name, ", Age:", doc.age);
console.log("Created At:", doc.createdAt);
console.log("Updated At:", doc.updatedAt);
});
};

const updateStudent = async () => {
let doc = await Student.findOneAndUpdate(
{ name: "Rahul" },
{ age: 25 },
{ new: true }
);
console.log("Name:", doc.name, ", Age:", doc.age);
console.log("Created At:", doc.createdAt);
console.log("Updated At:", doc.updatedAt);
};

const start = async () => {
await saveStudent("Rahul", 15);
setTimeout(function () {
updateStudent();
}, 3000);
};

start();

Step 5: Run the code using the following command:

node index.js

Output: The output in the command line is as follows. The output shows that the document is updated after 3 seconds.

Output of MongoDB: The following field will now reflect in the database also, as shown in the image below:

Explanation:

  • Creating the Mongoose Schema with Timestamps: The { timestamps: true } option in the schema tells Mongoose to automatically add and update the createdAt and updatedAt fields automatically for each document.
  • Saving a Document: When we add a new document and save it by calling the save() method, Mongoose automatically sets the createdAt and updatedAt fields to the current date and time.
  • Updating a Document: When we update a document with the findOneAndUpdate() method, the updatedAt field is also updated automatically.

Conclusion

Mongoose timestamps is a straightforward but useful feature to keep track of when documents are created and updated within MongoDB. By applying the timestamps: true option within your schema, you can have createdAt and updatedAt fields automatically managed without manually keeping track of them. This is a valuable feature for any number of use cases ranging from auditing and versioning to data synchronization. We should now have a good idea on how to use timestamps in Mongoose to improve your applications by following this article.


Next Article

Similar Reads