乐闻世界logo
搜索文章和话题

Mongoose 中哪种 schema 类型适合使用时间戳?

5 个月前提问
3 个月前修改
浏览次数48

6个答案

1
2
3
4
5
6

在Mongoose中,时间戳通常适用于想要自动记录文档创建和最后修改时间的场景。启用时间戳的模式选项会为你的文档添加两个字段:createdAtupdatedAtcreatedAt 字段会在文档首次保存到数据库时设置,而 updatedAt 字段会在每次调用 save() 方法更新文档时自动更新。

以下是使用时间戳的适合场景:

  1. 用户账户系统:在用户账户系统中,可以通过时间戳轻松追踪用户账户的创建时间和上次更新时间,这对于审计和监控账户行为很有帮助。

  2. 日志记录:如果你正在构建一个需要日志记录的系统,如错误日志或用户活动日志,时间戳是记录事件发生时间的理想方式。

  3. 内容管理系统 (CMS):在CMS中,内容项(如文章、页面或评论)通常需要记录发布和编辑的时间戳,以便追踪内容的版本和历史。

  4. 电子商务平台:在订单管理中,记录订单创建和修改时间对于订单处理流程和客户服务至关重要。

  5. 博客平台:博客文章通常会展示发布和最后修改的日期,通过时间戳可以自动化这一过程。

  6. 任务跟踪系统:在任务或票据等跟踪系统中,了解任务何时被创建和最后更新对于项目管理非常重要。

下面是一个启用时间戳的Mongoose模式的示例:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; const UserSchema = new Schema( { username: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true } // 其他字段... }, { timestamps: true // 启用时间戳 } ); const User = mongoose.model('User', UserSchema); // 当你使用 User 模型创建新用户时,Mongoose会自动设置 createdAt 和 updatedAt 字段。

在这个用户账户模型示例中,启用时间戳选项后,每个用户文档都将自动包含 createdAtupdatedAt 字段,这可以帮助我们跟踪用户的注册时间以及他们信息的最后更新时间。如果以后需要对用户表进行数据分析或维护,这些时间戳将非常有用。

2024年6月29日 12:07 回复

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):

shell
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

2024年6月29日 12:07 回复

The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

shell
var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.

2024年6月29日 12:07 回复

In case you want custom names for your createdAt and updatedAt

shell
const mongoose = require('mongoose'); const { Schema } = mongoose; const schemaOptions = { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, }; const mySchema = new Schema({ name: String }, schemaOptions);
2024年6月29日 12:07 回复

Mongoose now supports the timestamps in schema.

shell
const item = new Schema( { id: { type: String, required: true, }, { timestamps: true }, );

This will add the createdAt and updatedAt fields on each record create.

Timestamp interface has fields

shell
interface SchemaTimestampsConfig { createdAt?: boolean | string; updatedAt?: boolean | string; currentTime?: () => (Date | number); }

This would help us to choose which fields we want and overwrite the date format.

2024年6月29日 12:07 回复

你的答案