Converting a mongo stored date back into milliseconds since Unix epoch when loaded?

Converting a mongo stored date back into milliseconds since Unix epoch when loaded?

Problem

I am using Mongoose & Node.js for my webserver.

As a part of one of my document schemas, I have a ‘timestamp’ field. The line for it in the schema is: timestamp: { type: Date, default: Date.now }

This works fine, and allows me to retrieve documents based on the timestamp, however, this saves as the ISODate format as described here: http://docs.mongodb.org/manual/core/document/#date, like this:

"timestamp":"2013-04-04T19:31:38.514Z"

I don’t mind this, but I send this to the client as is. This means I have to use Date.parse() at the client end before I can comparative operations with it.

Is there any way to either store the date as an integer, or automatically convert it to one when it’s retrieved?

Is there any reason I should keep it how it is, and just deal with it at the client end?

Thanks in advance.

Problem courtesy of: Ed Hinchliffe

Solution

You can add the numerical milliseconds version of timestamp as a virtual attribute on the schema:

schema.virtual('timestamp_ms').get(function() {
  return this.timestamp.getTime();
});

Then you can enable the virtual field’s inclusion in toObject calls on model instances via an option on your schema:

var schema = new Schema({
  timestamp: Date
}, {
  toObject: { getters: true }
});
Solution courtesy of: JohnnyHK

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *