Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 923
Ed_ Avatar asked Apr 05 '13 09:04

Ed_


4 Answers

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 }
});
like image 126
JohnnyHK Avatar answered Nov 17 '22 22:11

JohnnyHK


var schema = new Schema({
  timestamp: {type:Number, default: new Date().getTime()}
});

Hope this will solve your issue.

like image 39
Pranav Anand Avatar answered Nov 17 '22 21:11

Pranav Anand


As a best practice, I would say: keep your data the type it deserves.

Anyway, if your client needs to treat with numbers, you can simply pass the date as milliseconds to the client, and still work with Date objects in Node.

Just call timestamp.getTime() and ta-da, you have your unix timestamp ready for the client.

like image 4
gustavohenke Avatar answered Nov 17 '22 20:11

gustavohenke


This works fine for me

db.eurusd.ticks.findOne({_id:ObjectId("518636777055000000000000")}).t.getTime()

returns time in miliseconds, where returned document has structure

{
 "_id" : ObjectId("518636777055000000000000"),
 "t" : ISODate("2013-05-05T10:37:43Z"), // date data type
 "ask" : "Joe",
 "bid" : 33
}
like image 3
Jaro Avatar answered Nov 17 '22 22:11

Jaro