Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

node.js - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...