0
0
MongodbHow-ToBeginner · 3 min read

How to Use Timestamps in Mongoose for MongoDB

In Mongoose, you can enable automatic timestamps by adding timestamps: true in your schema options. This adds createdAt and updatedAt fields to your documents, which Mongoose updates automatically when documents are created or modified.
📐

Syntax

To use timestamps in Mongoose, add timestamps: true inside the schema options object. This tells Mongoose to add two fields: createdAt and updatedAt. These fields store the date and time when the document was created and last updated.

javascript
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
  name: String
}, { timestamps: true });
💻

Example

This example shows how to create a Mongoose model with timestamps enabled. When you save a new document, Mongoose automatically sets createdAt and updatedAt. When you update the document, updatedAt changes to the current time.

javascript
const mongoose = require('mongoose');

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  const userSchema = new mongoose.Schema({
    name: String
  }, { timestamps: true });

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

  // Create a new user
  const user = new User({ name: 'Alice' });
  await user.save();
  console.log('After creation:', user);

  // Wait 1 second then update
  await new Promise(resolve => setTimeout(resolve, 1000));
  user.name = 'Alice Updated';
  await user.save();
  console.log('After update:', user);

  await mongoose.disconnect();
}

run();
Output
After creation: { _id: ..., name: 'Alice', createdAt: 2024-06-01T12:00:00.000Z, updatedAt: 2024-06-01T12:00:00.000Z, __v: 0 } After update: { _id: ..., name: 'Alice Updated', createdAt: 2024-06-01T12:00:00.000Z, updatedAt: 2024-06-01T12:00:01.000Z, __v: 0 }
⚠️

Common Pitfalls

  • Not enabling timestamps in the schema options means no automatic date fields are added.
  • Manually setting createdAt or updatedAt can cause conflicts; let Mongoose handle them.
  • Using older Mongoose versions may require different syntax; always use a recent stable version.
javascript
const wrongSchema = new mongoose.Schema({
  name: String,
  createdAt: Date,
  updatedAt: Date
});

// This disables automatic timestamps and requires manual management, which is error-prone.

const rightSchema = new mongoose.Schema({
  name: String
}, { timestamps: true });
📊

Quick Reference

OptionDescription
timestamps: trueAdds createdAt and updatedAt fields automatically.
createdAtDate when the document was created.
updatedAtDate when the document was last updated.
Custom field namesUse { timestamps: { createdAt: 'created_on', updatedAt: 'updated_on' } } to rename fields.

Key Takeaways

Enable timestamps by adding { timestamps: true } in your schema options.
Mongoose automatically manages createdAt and updatedAt fields for you.
Avoid manually setting timestamp fields to prevent conflicts.
You can customize timestamp field names using an object instead of true.
Always use a recent Mongoose version for best timestamp support.