更新:(5年后)
Note: If you decide to use Kappa Architecture (Event Sourcing + CQRS), then you do not need updated date at all. Since your data is an immutable, append-only event log, you only ever need event created date. Similar to the Lambda Architecture, described below. Then your application state is a projection of the event log (derived data). If you receive a subsequent event about existing entity, then you'll use that event's created date as updated date for your entity. This is a commonly used (and commonly misunderstood) practice in miceroservice systems.
更新:(4年后)
如果你使用ObjectId作为你的_id字段(通常情况下),那么你所需要做的就是:
let document = {
updatedAt: new Date(),
}
查看下面我的原始答案,了解如何从_id字段获取创建的时间戳。
如果你需要使用外部系统的id,请检查Roman Rhrn Nesterov的答案。
更新:(2.5年后)
你现在可以在猫鼬>= 4.0版本中使用#时间戳选项。
let ItemSchema = new Schema({
name: { type: String, required: true, trim: true }
},
{
timestamps: true
});
如果设置了时间戳,猫鼬将createdAt和updatedAt字段分配给你的模式,分配的类型是Date。
你也可以指定时间戳字段的名称:
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
Note: If you are working on a big application with critical data you should reconsider updating your documents. I would advise you to work with immutable, append-only data (lambda architecture). What this means is
that you only ever allow inserts. Updates and deletes should not be
allowed! If you would like to "delete" a record, you could easily
insert a new version of the document with some timestamp/version
filed and then set a deleted field to true. Similarly if you want
to update a document – you create a new one with the appropriate
fields updated and the rest of the fields copied over.Then in order to
query this document you would get the one with the newest timestamp or
the highest version which is not "deleted" (the deleted field is undefined or false`).
Data immutability ensures that your data is debuggable – you can trace
the history of every document. You can also rollback to previous
version of a document if something goes wrong. If you go with such an
architecture ObjectId.getTimestamp() is all you need, and it is not
Mongoose dependent.
最初的回答:
如果你使用ObjectId作为你的身份字段,你不需要created_at字段。ObjectIds有一个叫做getTimestamp()的方法。
ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
这将返回以下输出:
ISODate("2012-10-15T21:26:17Z")
更多信息在这里我如何提取一个Mongo ObjectID创建的日期
为了添加updated_at文件,你需要使用这个:
var ArticleSchema = new Schema({
updated_at: { type: Date }
// rest of the fields go here
});
ArticleSchema.pre('save', function(next) {
this.updated_at = Date.now();
next();
});