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.
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 }
});
var schema = new Schema({
timestamp: {type:Number, default: new Date().getTime()}
});
Hope this will solve your issue.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With