Converting A Mongo Stored Date Back Into Milliseconds Since Unix Epoch When Loaded?


Answer :

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.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable