本文介绍了猫鼬中哪个SchemaType最适合时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mongoose,MongoDB和Node.

我想定义一个模式,其中的一个字段是日期\时间戳.

我想使用此字段来返回最近5分钟内已更新的所有记录.

由于在Mongoose中我无法使用Timestamp()方法,因此我了解到,我唯一的选择是使用以下Javascript方法:

time : { type: Number, default: (new Date()).getTime() } 

这可能不是查询庞大数据库的最有效方法.如果有人可以分享一种更有效的实施方式,我将不胜感激.

有什么方法可以用Mongoose来实现,并且可以使用MongoDB时间戳吗?

解决方案

编辑-2016年3月20日

猫鼬现在支持收藏的时间戳.

请在下面考虑@bobbyz的答案.也许这就是您要寻找的.

原始答案

猫鼬支持Date类型(基本上是时间戳):

time : { type : Date, default: Date.now }

使用上述字段定义,每当您保存未设置time字段的文档时,Mongoose都会使用当前时间填写该字段.

来源: http://mongoosejs.com/docs/guide.html

I'm using Mongoose, MongoDB, and Node.

I would like to define a schema where one of its fields is a date\timestamp.

I would like to use this field in order to return all of the records that have been updated in the last 5 minutes.

Due to the fact that in Mongoose I can't use the Timestamp() method I understand that my only option is to use the following Javascript method:

time : { type: Number, default: (new Date()).getTime() } 

It's probably not the most efficient way for querying a humongous DB. I would really appreciate it if someone could share a more efficient way of implementing this.

Is there any way to implement this with Mongoose and be able to use a MongoDB timestamp?

解决方案

Edit - 20 March 2016

Mongoose now support timestamps for collections.

Please consider the answer of @bobbyz below. Maybe this is what you are looking for.

Original answer

Mongoose supports a Date type (which is basically a timestamp):

time : { type : Date, default: Date.now }

With the above field definition, any time you save a document with an unset time field, Mongoose will fill in this field with the current time.

Source: http://mongoosejs.com/docs/guide.html

这篇关于猫鼬中哪个SchemaType最适合时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 08:02