If you want to automatically track the creation and modification dates of your documents in MongoDB, you can add a timestamps
flag to your schema. This will ensure that each document includes a createdAt
field for creation date and an updatedAt
field for modification date. For example:
const mongoose = require("mongoose");
const TaskSchema = new mongoose.Schema(
{
task: {
type: String,
required: [true, "Please enter a task name"],
},
info: {
type: String,
required: [true, "Please provide details for the task"],
},
due: {
type: Date,
required: [true, "Please provide a due date"],
},
complete: {
type: Boolean,
required: true,
default: false,
},
createdBy: {
type: mongoose.Types.ObjectId,
ref: "User",
required: [true, "please provide user"],
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Task", TaskSchema);
By setting the timestamps flag to true in the above example, every time you retrieve a task document, it will include the creation and update timestamps as shown here:
https://i.sstatic.net/xSf6H.png