node.js - 将 created_at 和 updated_at 字段添加到 Mongoose

有没有办法将 created_at 和 updated_at 字段添加到 mongoose 架构,而不必在每次调用 new MyModel() 时都传递它们?

created_at 字段将是一个日期,并且仅在创建文档时添加。 每当对文档调用 save() 时,updated_at 字段都会更新为新日期。

我已经在我的架构中尝试过这个,但是除非我明确添加它,否则该字段不会显示:

var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true },
    created_at    : { type: Date, required: true, default: Date.now }
});

最佳答案

更新:(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 年后)

您现在可以使用 #timestamps Mongoose 版本 >= 4.0 的选项。

let ItemSchema = new Schema({
  name: { type: String, required: true, trim: true }
},
{
  timestamps: true
});

如果设置时间戳,mongoose 会将 createdAtupdatedAt 字段分配给您的架构,分配的类型是 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()

This will return the following output:

ISODate("2012-10-15T21:26:17Z")

More info here How do I extract the created date out of a Mongo ObjectID

In order to add updated_at filed you need to use this:

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

关于node.js - 将 created_at 和 updated_at 字段添加到 Mongoose 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12669615/

相关文章:

mongodb - 如何检查数组字段是否包含唯一值或 MongoDB 中的另一个数组?

mongodb - 无法连接到服务器 127.0.0.1 :27017

mongodb - Node.js Mongoose.js 字符串到 ObjectId 函数

node.js - mongoError : Topology was destroyed

mongodb - 如何解决 MongoDB 中缺少事务的问题?

mongodb - 如何在 mongodb 上导入 .bson 文件格式

mongodb - Mongodb中的保存和插入有什么区别?

mongodb - 如何更改字段的类型?

node.js - 在 Mongoose 中,我如何按日期排序? (node.js)

mongodb - 了解 MongoDB BSON 文档大小限制