There are cases when you would like Mongoose to implicitly add the current timestamp to an "updatedAt" field.
Mongoose API documentation has an example of the same which uses Date.now as the default parameter.
Eg:
For those who aren't clear about the difference both statements make in the above context of default value specification:-
Mongoose API documentation has an example of the same which uses Date.now as the default parameter.
Eg:
var Schema = require('mongoose').Schema; var mySchema = new Schema({ title: { type: String }, updatedAt: { type : Date, default : Date.now } });But chances are there for someone to replace Date.now with the often interchangeably used new Date() expression in JavaScript. Ah! at least I did this in one of the schema definitions which brought unexpected results. Such errors are difficult to catch during the early stages and might stay hidden in the background for a while, until someone somewhere gets a heavy surprise out of it.
For those who aren't clear about the difference both statements make in the above context of default value specification:-
It is executed only once when the server starts up and the Mongoose Schema are loaded. All the subsequent calls to get the default value, will get the same historic date value when the schema was initialised.
We can be sure that whenever it is invoked we get current timestamp as expected.