This content originally appeared on CodeSource.io and was authored by Deven
In this article, You will learn how to use Mongoose timestamps.
Mongoose schemas have a timestamps option that informs Mongoose to automatically manage createdAt and updatedAt properties on your documents. Everything in Mongoose starts with a Schema. MongoDB collection maps each schema and within that collection, it defines the shape of the documents.
Let’s assume you have created an UserModel for stored user information. You want to know when a particular user has been created or when a particular user information has been changed. So how you will implement it? You can simply enable the Mongoose schemas timestamps option in your userSchema . Follow the code below:
const userSchema = mongoose.Schema(
{
email: String,
},
{ timestamps: true }
);
const User = mongoose.model("User", userSchema);
const newUser = await User.create({ email: "abc@gmail.com" });
newUser.createdAt; // 2021-10-15T21:19:00.000Z
newUser.updatedAt; // 2021-10-15T21:19:00.000Z
newUser.createdAt instanceof Date; // true
Mongoose adds createdAt and updatedAt properties to your schema when you enable timestamps. By default, createdAt and updatedAt are of type Date. When a user updates a document, Mongoose automatically increments updatedAt.
newUser.email = "test@gmail.com";
await newUser.save();
newUser.createdAt; // 2021-10-15T21:19:00.000Z
newUser.updatedAt; // 2021-10-15T21:29:00.000Z
Although timestamps were set in the schema, you can skip timestamps for specific users. Specific mongoose model write operations allow you to perform this action. You have to set timestamps false to do this and the time will not be updated on that specific operation.
const userSchema = mongoose.Schema({
email: String
}, { timestamps: true });
const User = mongoose.model('User', userSchema);
const newUser = await User.findOneAndUpdate({email: 'abc@gmail.com'}, {email:'test@gmail.com'},
{new:true, upsert: true, timestamps:false});
Suppose you want to prevent only one of those from updating. You don’t need to set timestamps to false as the value. Instead of doing this, you can create an object with key-value pairs. The keys can be createdAt or updatedAt and the values can be true or false depending on what you need.
const userSchema = mongoose.Schema({
email: String
}, { timestamps: true });
const User = mongoose.model('User', userSchema);
const newUser = await User.findOneAndUpdate({email: 'abc@gmail.com'}, {email:'test@gmail.com'},
{new:true, upsert: true, timestamps:{createdAt:false, updatedAt:true}});
You can work with Date types sufficiently but in addition you can also make Mongoose store timestamps as seconds since January 1, 1970 (the Unix epoch). Mongoose schemas provides timestamps.currentTime as a option that lets you pass a custom function to use for getting the current time.
const opts = {
// Make Mongoose use Unix time (seconds since Jan 1, 1970)
timestamps: { currentTime: () => Math.floor(Date.now() / 1000) },
};
const userSchema = mongoose.Schema(
{
email: String,
},
opts
);
Important : You need to be careful to strip out createdAt from any request bodies. Otherwise, a bug or a malicious user might set an incorrect createdAt. Because createdAt shouldn’t change once the document is created. To avoid this unwanted situation you can make a property immutable. Mongoose will disallow changing createdAt, if you mark createdAt as immutable.
const userSchema = mongoose.Schema(
{
email: String,
},
createdAt: {
type: Date,
immutable: true // Make `createdAt` immutable
},
{ timestamps: true }
);
const User = mongoose.model("User", userSchema);
const newUser = await User.create({ email: "abc@gmail.com" });
console.log(newUser.createdAt); // 2021-10-15T21:19:00.000Z
// Since `createdAt` is immutable, Mongoose ignores the update
// to `createdAt`
newUser.set({ createdAt: new Date('2021-10-15'), email: "abc@gmail.com" });
await newUser.save();
console.log(newUser.email); // 'abc@gmail.com'
console.log(newUser.createdAt); // 2021-10-15T21:19:00.000Z
Note : To make a property immutable you need to install Mongoose 5.6.0 or above.
This is all about mongoose timestamp and you can learn how to use it.
The post Learn How to use Mongoose timestamps appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-10-16T09:18:39+00:00) Learn How to use Mongoose timestamps. Retrieved from https://www.scien.cx/2021/10/16/learn-how-to-use-mongoose-timestamps/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.