将 mongo 存储的日期转换回自 Unix 纪元加载后的毫秒数? [英] Converting a mongo stored date back into milliseconds since Unix epoch when loaded?
问题描述
我正在使用猫鼬 &我的网络服务器的 Node.js.
作为我的一个文档架构的一部分,我有一个时间戳"字段.模式中的这一行是:timestamp: { type: Date, default: Date.now }
这很好用,并允许我根据时间戳检索文档,但是,这将保存为 ISODate 格式,如下所述:http://docs.mongodb.org/manual/core/document/#date,像这样:
"timestamp":"2013-04-04T19:31:38.514Z"
我不介意这个,但我按原样发送给客户.这意味着我必须在客户端使用 Date.parse() 才能与其进行比较操作.
有没有办法将日期存储为整数,或者在检索时自动将其转换为整数?
是否有任何理由让我保持原样,并在客户端处理它?</p>
提前致谢.
您可以将 timestamp
的数字毫秒版本添加为 virtual 架构上的属性:
schema.virtual('timestamp_ms').get(function() {返回 this.timestamp.getTime();});
然后,您可以通过架构上的选项在模型实例上的 toObject
调用中启用虚拟字段的包含:
var schema = new Schema({时间戳:日期}, {toObject: { 吸气剂: 真 }});
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 }
});
这篇关于将 mongo 存储的日期转换回自 Unix 纪元加载后的毫秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!