Thursday, 27 November 2014

Mongoose default current timestamp in Schema

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:
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:-
Using new Date() constructor
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.
Using Date.now method
We can be sure that whenever it is invoked we get current timestamp as expected.
• • •