mongodb date default value code example

Example: mongodb default date

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.

Tags:

Misc Example