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.
Similar Reads
Mongoose Plugins
Plugins are a technique for reusing logic in multiple mongoose schemas. A plugin is similar to a method that you can use in your schema and reuse repeatedly over different instances of the schema. The main purpose of plugins is to modify your schemas. Plugins don't have anything to do with models or
5 min read
PostgreSQL TO_TIMESTAMP() Function
In PostgreSQL, managing and manipulating date and time values is important, especially when they are stored as strings. The to_timestamp function allows us to convert textual representations of dates and times into a valid timestamp format and making it easier to work with them in queries, calculati
5 min read
PHP | date_timestamp_set() Function
The date_timestamp_set() function is an inbuilt function in PHP which is used to sets the date and time based on an Unix timestamp. This function returns the DateTime object for method chaining or False on failure. Syntax: Procedural style: date_timestamp_set( $object, $unixtimestamp ) Object orient
2 min read
PHP | date_timestamp_get() Function
The date_timestamp_get() function is an inbuilt function in PHP which is used to gets the Unix timestamp. This function returns the Unix timestamp representing the date. Syntax: Procedural style: int date_timestamp_get( $object ) Object oriented style: int DateTime::getTimestamp( void ) int DateTime
1 min read
Pandas Timestamp To Datetime
A timestamp is a representation of a specific point in time, expressed as a combination of date and time information. In data processing, timestamps are used to note the occurrence of events, record the time at which data was generated or modified, and provide a chronological ordering of data.Pandas
3 min read
HTML DOM timeStamp Event Property
The timeStamp property in the HTML DOM refers to a read-only property that returns the time (in milliseconds) at which an event was created. The value is measured relative to the UNIX epoch (January 1, 1970, 00:00:00 UTC). This property is commonly used to determine the timing of events and can be u
1 min read
How To Make Timestamps On Discord
Understanding Discord's timestamp format is essential for accurately marking time in messages, especially when dealing with users across different time zones. A Discord timestamp converter helps to easily translate timestamps between regions, considering the user's Discord timestamp timezone. Using
6 min read
Moment.js Parsing Unix Timestamp (seconds)
Moment.js is a date library for JavaScript that parses, validates, manipulates, and formats dates. We can use the moment.unix() function to parse unix timestamps (seconds). The moment.unix() function is used to create a moment using Unix Timestamp, seconds since the Unix Epoch (Jan 1 1970 12AM UTC).
1 min read
Get Current Timestamp Using Python
A timestamp is a sequence of characters that represents the date and time at which a particular event occurred, often accurate to fractions of a second. Timestamps are essential in logging events, tracking files, and handling date-time data in various applications. There are 3 different ways to get
2 min read
jQuery event.timeStamp Property
The jQuery event.timeStamp is an inbuilt property that is used to measure the difference in milliseconds between the time of the event created by the browser and January 1, 1970. Syntax: event.timeStampParameter: It does not accept any parameter because it is a property, not a function. Example 1: T
2 min read