How create a Date field with default value as the current timestamp in MongoDb?

Thats pretty simple!
When you’re using Mongoose for example, you can pass functions as a default value.
Mongoose then calls the function for every insertion.

So in your Schema you would do something like:

 {
   timestamp: { type: Date, default: Date.now},
   ...
 }

Remember to only pass the function object itself Date.now and not the value of the function call Date.now()as this will only set the Date once to the value of when your Schema got created.

This solution applies to Mongoose & Node.Js and I hope that is your usecase because you did not specify that more precisely.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)