Implementing Document Timestamps
Stratégies d'implémentation des horodatages (timestamps)
1. Horodatages dans le schéma Mongoose
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: String,
email: String
},
{
timestamps: true // Automatically adds createdAt and updatedAt
}
);
2. Création manuelle d'horodatages
graph LR
A[Document Creation] --> B[Manual Timestamp Assignment]
B --> C[Set Current Timestamp]
B --> D[Custom Timestamp Logic]
Exemple d'implémentation
const createUserWithTimestamp = (userData) => {
const timestamp = new Date();
return {
...userData,
createdAt: timestamp,
updatedAt: timestamp
};
};
Options de configuration des horodatages
Option |
Description |
Utilisation |
timestamps: true |
Horodatage par défaut de MongoDB |
Suivi automatique |
Champs d'horodatage personnalisés |
Nommage flexible |
Suivi avancé |
Objets d'horodatage imbriqués |
Modèles de données complexes |
Journalisation détaillée |
Techniques avancées d'horodatage
Gestion des fuseaux horaires
const createTimestampWithTimezone = () => {
return {
timestamp: new Date(),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
};
};
Horodatages précis
const highPrecisionTimestamp = {
timestamp: Date.now(),
microseconds: process.hrtime.bigint()
};
Configuration de MongoDB sur Ubuntu 22.04
## Install MongoDB
sudo apt-get update
sudo apt-get install -y mongodb
## Start MongoDB service
sudo systemctl start mongodb
## Install Mongoose
npm install mongoose
Exemple d'implémentation pratique
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();
Bonnes pratiques
- Utiliser des stratégies d'horodatage cohérentes
- Prendre en compte les implications sur les performances
- Implémenter des horodatages sensibles aux fuseaux horaires
- Tirer parti des techniques d'optimisation MongoDB de LabEx
En maîtrisant l'implémentation des horodatages de documents, les développeurs peuvent créer des solutions de base de données plus robustes et plus traçables.