Home » Timestamps in Mongoose

Timestamps in Mongoose

Timestamps in Mongoose

Timestamps are a useful feature in Mongoose that automatically keep track of when a document is created and last modified. This feature is important for applications that need to monitor data changes over time, such as logging, auditing, or tracking user activity

Timestamps in Mongoose automatically add createdAt and updatedAt fields to your schema, which store the document’s creation time and last modification time, respectively. These fields are automatically updated by Mongoose each time a document is created or edited, without requiring manual intervention.

How Timestamps Work

  1. createdAt: This field is automatically set to the date and time when the document is first created.
  2. updatedAt: This field is automatically set to the date and time whenever the document is updated.

Mongoose uses these fields to keep track of the lifecycle of each document, ensuring you have an accurate record of when data was created and last modified.

Benefits of Using Timestamps

  1. Automatic Tracking: Automatically keeps track of when documents are created and modified, reducing the need for manual handling.
  2. Data Auditing: Facilitates auditing and logging of data changes over time, making it easier to track and debug issues.
  3. Time-based Queries: Enables time-based queries, such as finding documents created or updated within a specific time range.
  4. Version Control: Helps implement version control mechanisms by tracking document updates.

Examples

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  }
}, { timestamps: true });

const User = mongoose.model('User', userSchema);

async function createAndUpdateUser() {
  // Creating a new user
  let user = new User({ username: 'john_doe', email: 'john@example.com' });
  await user.save();
  console.log('User created:', user);

  // Updating the user's email
  user.email = 'john.doe@example.com';
  await user.save();
  console.log('User updated:', user);
}

createAndUpdateUser().then(() => mongoose.disconnect());
JavaScript

In this example:

  • When the user is first created, the createdAt and updatedAt fields are both set to the current date and time.
  • When the user’s email is updated, the updatedAt field is automatically updated to reflect the new modification time, while the createdAt field remains unchanged.

Customizing Timestamps

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  }
}, { 
  timestamps: { 
    createdAt: 'created_at', 
    updatedAt: 'updated_at' 
  }
});
JavaScript

In this example, the createdAt field is renamed to created_at and the updatedAt field is renamed to updated_at.

Practical Examples

Creating a Document with Timestamps

When a document is created, Mongoose automatically sets the createdAt and updatedAt fields:

const newUser = new User({
    username: 'jane_doe',
    email: 'jane.doe@example.com'
});

newUser.save()
    .then(user => console.log('User created:', user))
    .catch(err => console.error('Error creating user:', err));
JavaScript

Output

{
    "_id": "60c72b2f9b1e8c3f4c8b4567",
    "username": "jane_doe",
    "email": "jane.doe@example.com",
    "createdAt": "2023-06-18T10:00:00Z",
    "updatedAt": "2023-06-18T10:00:00Z",
    "__v": 0
}
JSON

Updating a Document with Timestamps

When a document is updated, Mongoose automatically updates the updatedAt field:

User.findByIdAndUpdate('60c72b2f9b1e8c3f4c8b4567', { username: 'jane_doe_updated' }, { new: true })
    .then(user => console.log('User updated:', user))
    .catch(err => console.error('Error updating user:', err));
JavaScript

Output

{
    "_id": "60c72b2f9b1e8c3f4c8b4567",
    "username": "jane_doe_updated",
    "email": "jane.doe@example.com",
    "createdAt": "2023-06-18T10:00:00Z",
    "updatedAt": "2023-06-18T12:00:00Z",
    "__v": 0
}
JSON

Conclusion

Timestamps in Mongoose provide a simple yet powerful way to track the creation and modification times of documents. By enabling timestamps, you can automatically maintain audit trails, facilitate debugging, and implement time-based features in your MongoDB-driven applications. The automatic handling of timestamps simplifies your code and ensures consistent and accurate tracking of data changes.

Frequently Asked Questions

1. Can I disable automatic updates to the updatedAt field for certain operations?

Yes, you can disable automatic updates to the updatedAt field by using the timestamps: false option in the update query.

2. Can I manually set the createdAt and updatedAt fields?

Yes, you can manually set these fields when creating or updating documents, but Mongoose will override them on subsequent operations unless configured otherwise.

3. How do I query documents based on their timestamp fields?

You can use standard MongoDB query operators to filter documents based on createdAt and updatedAt fields, such as $gte, $lte, $lt, and $gt.