Sling Academy
Home/MongoDB/MongoDB createdAt and updatedAt fields: A practical guide (with examples)

MongoDB createdAt and updatedAt fields: A practical guide (with examples)

Last updated: February 03, 2024

Introduction

Working with dates in a database can be a crucial aspect of an application, especially when you want to keep track of when data is created and modified. MongoDB, a popular NoSQL database, has capabilities that can help in this area, although it may not be immediately clear to beginners how to implement these features.

Understanding the Basics

In MongoDB, there is no built-in functionality for createdAt and updatedAt fields that you would find in some other databases or ORMs. Nevertheless, you can achieve similar functionality by using MongoDB’s schema validation feature or by leveraging Mongoose if you’re working in a Node.js environment.

Using MongoDB Shell

Let’s start with an example to create a collection that automatically adds createdAt and updatedAt fields when you insert a document. Unfortunately, MongoDB by itself doesn’t add timestamps, so you must manually insert the date values when you create or update documents.

 db.products.insertOne({
   name: 'Coffee Mug',
   price: 12.99,
   createdAt: new Date(),
   updatedAt: new Date()
 })

Note that you’ve had to manually add the date by calling new Date(). It’s straightforward but can become cumbersome and error-prone as the application grows.

Using MongoDB inbuilt operators

You can use inbuilt MongoDB operators like $currentDate to automatically set the date for updatedAt on update operations.

 db.products.updateOne(
   { _id: ObjectId('...') },
   {
     $set: { name: 'New Coffee Mug' },
     $currentDate: { updatedAt: true }
   }
 )

However, this requires you to remember to add $currentDate each time you perform an update operation.

Using Mongoose for Time Stamps

Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js, provides a more robust solution for handling createdAt and updatedAt fields. Let’s see how we can utilize Mongoose to streamline this process.

Enabling Timestamps in Mongoose Schema

 const mongoose = require('mongoose');

 const ProductSchema = new mongoose.Schema({
   name: {
     type: String,
     required: true
   },
   price: {
     type: Number,
     required: true
   }
 }, { timestamps: true });
 
 const Product = mongoose.model('Product', ProductSchema);

By simply adding `{ timestamps: true }` to your schema options, Mongoose automatically adds createdAt and updatedAt fields to your documents. These fields are automatically managed by Mongoose, so you don’t have to do anything extra when you create or update documents.

Advanced Usage

For more control over the naming of your timestamp fields or additional options, you can pass an options object to the timestamps configuration.

 const ProductSchema = new mongoose.Schema({
   name: {
     type: String,
     required: true
   },
   price: {
     type: Number,
     required: true
   }
 }, {
   timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
 });

Mongoose also allows for pre and post middlewares which can be used to run custom logic before or after certain actions, such as saving a document. This could be used to further manage timestamps in a more granular way.

Common Problems and Solutions

Let’s address some common issues you might face when dealing with timestamps.

Time Zone Issues

MongoDB stores dates in UTC by default. It’s important to be mindful of time zones when storing and retrieving dates, especially if your application users are spread across different time zones. In such cases, you should convert the dates to the user’s local time zone in your application logic.

Querying Date Ranges

Using MongoDB’s built-in query operators, you can fetch documents based on date ranges which can be useful for reports or analytics purposes.

 db.products.find({
   createdAt: {
     $gte: new Date('2023-01-01'),
     $lt: new Date('2023-02-01')
   }
 })

This query will return all documents that were created in January 2023, taking advantage of the $gte (greater than or equal to) and $lt (less than) operators.

Error Handling

When working with dates, it’s important to handle potential errors appropriately. Make sure your application logic accounts for various date-related issues, such as incorrect date formats, null values, or time zone discrepancies.

MongoDB Compass and Robo 3T

Tools like MongoDB Compass and Robo 3T offer user-friendly interfaces for working with your MongoDB collections, including features for inserting, reading, updating, and deleting documents. However, they don’t inherently solve the timestamp issue. You would still need to follow the practices outlined above, using either the native MongoDB operators or by employing a tool like Mongoose when working with Node.js applications.

Conclusion

In conclusion, managing createdAt and updatedAt fields in MongoDB can range from manual entry of date values to automated solutions with Mongoose. Understanding how to properly handle timestamps will ensure your MongoDB documents maintain accurate historical data, which is invaluable for tracking changes and maintaining the integrity of your application’s data.

Next Article: Working with Change Streams in MongoDB (with examples)

Previous Article: Understanding $slice operator in MongoDB (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)