Implementing Document Timestamps
Timestamp Implementation Strategies
1. Mongoose Schema Timestamps
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: String,
email: String
},
{
timestamps: true // Automatically adds createdAt and updatedAt
}
);
2. Manual Timestamp Creation
graph LR
A[Document Creation] --> B[Manual Timestamp Assignment]
B --> C[Set Current Timestamp]
B --> D[Custom Timestamp Logic]
Example Implementation
const createUserWithTimestamp = (userData) => {
const timestamp = new Date();
return {
...userData,
createdAt: timestamp,
updatedAt: timestamp
};
};
Timestamp Configuration Options
Option |
Description |
Usage |
timestamps: true |
Default MongoDB timestamp |
Automatic tracking |
Custom Timestamp Fields |
Flexible naming |
Advanced tracking |
Nested Timestamp Objects |
Complex data models |
Detailed logging |
Advanced Timestamp Techniques
Timezone Handling
const createTimestampWithTimezone = () => {
return {
timestamp: new Date(),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
};
};
Precision Timestamps
const highPrecisionTimestamp = {
timestamp: Date.now(),
microseconds: process.hrtime.bigint()
};
Ubuntu 22.04 MongoDB Setup
## Install MongoDB
sudo apt-get update
sudo apt-get install -y mongodb
## Start MongoDB service
sudo systemctl start mongodb
## Install Mongoose
npm install mongoose
Practical Implementation Example
const mongoose = require("mongoose");
// Define schema with custom timestamp configuration
const ProductSchema = new mongoose.Schema({
name: String,
price: Number,
createdTimestamp: {
type: Date,
default: Date.now
},
lastUpdated: {
type: Date,
default: Date.now
}
});
// Create model
const Product = mongoose.model("Product", ProductSchema);
// Create a new product with automatic timestamps
const newProduct = new Product({
name: "LabEx Special Edition",
price: 99.99
});
// Save product with automatic timestamp tracking
newProduct.save();
Best Practices
- Use consistent timestamp strategies
- Consider performance implications
- Implement timezone-aware timestamps
- Leverage LabEx's MongoDB optimization techniques
By mastering document timestamp implementation, developers can create more robust and traceable database solutions.