node.js 将 created_at 和 updated_at 字段添加到猫鼬模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12669615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add created_at and updated_at fields to mongoose schemas
提问by chovy
Is there a way to add created_at and updated_at fields to a mongoose schema, without having to pass them in everytime new MyModel() is called?
有没有办法将 created_at 和 updated_at 字段添加到猫鼬模式中,而不必在每次调用 new MyModel() 时将它们传递进来?
The created_at field would be a date and only added when a document is created. The updated_at field would be updated with new date whenever save() is called on a document.
created_at 字段将是一个日期,并且仅在创建文档时添加。每当在文档上调用 save() 时, updated_at 字段将使用新日期进行更新。
I have tried this in my schema, but the field does not show up unless I expcitly add it:
我已经在我的架构中尝试过这个,但是除非我明确添加它,否则该字段不会显示:
var ItemSchema = new Schema({
name : { type: String, required: true, trim: true }
, created_at : { type: Date, required: true, default: Date.now }
});
采纳答案by Binarytales
As of Mongoose 4.0 you can now set a timestamps option on the Schema to have Mongoose handle this for you:
从 Mongoose 4.0 开始,您现在可以在 Schema 上设置时间戳选项,让 Mongoose 为您处理:
var thingSchema = new Schema({..}, { timestamps: true });
You can change the name of the fields used like so:
您可以像这样更改使用的字段的名称:
var thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });
回答by Pavel Nikolov
UPDATE:(5 years later)
更新:(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.
注意:如果您决定使用Kappa 架构(事件溯源 + CQRS),那么您根本不需要更新日期。由于您的数据是不可变的、只能追加的事件日志,因此您只需要事件创建日期。类似于Lambda 架构,如下所述。那么您的应用程序状态是事件日志(派生数据)的投影。如果您收到有关现有实体的后续事件,那么您将使用该事件的创建日期作为实体的更新日期。这是微服务系统中常用(也常被误解)的做法。
UPDATE:(4 years later)
更新:(4年后)
If you use ObjectIdas your _idfield (which is usually the case), then all you need to do is:
如果您使用ObjectId作为您的_id字段(通常是这种情况),那么您需要做的就是:
let document = {
updatedAt: new Date(),
}
Check my original answer below on how to get the created timestamp from the _idfield.
If you need to use IDs from external system, then check Roman Rhrn Nesterov's answer.
在下面查看我的原始答案,了解如何从_id字段中获取创建的时间戳。如果您需要使用来自外部系统的 ID,请查看 Roman Rhrn Nesterov 的回答。
UPDATE:(2.5 years later)
更新:(2.5 年后)
You can now use the #timestampsoption with mongoose version >= 4.0.
您现在可以在mongoose版本 >= 4.0 中使用#timestamps选项。
let ItemSchema = new Schema({
name: { type: String, required: true, trim: true }
},
{
timestamps: true
});
If set timestamps, mongoose assigns createdAtand updatedAtfields to your schema, the type assigned is Date.
如果为您的架构设置时间戳、猫鼬分配createdAt和updatedAt字段,则分配的类型为Date.
You can also specify the timestamp fileds' names:
您还可以指定时间戳文件的名称:
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/versionfiled and then set adeletedfield totrue. 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" (thedeletedfield 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.
注意:如果您正在处理具有关键数据的大型应用程序,您应该重新考虑更新您的文档。我建议您使用不可变的、仅附加的数据(lambda 架构)。这意味着您只允许插入。不允许更新和删除!如果您想“删除”一条记录,您可以轻松地插入带有 some
timestamp/的文档的新版本,version然后将deleted字段设置为true. 类似地,如果你想更新一个文档——你创建一个新的,其中更新了适当的字段,其余的字段被复制了。然后为了查询这个文档,你将获得具有最新时间戳或最高版本的文档。没有被“删除”(deleted字段未定义或为假`)。数据不变性确保您的数据是可调试的——您可以跟踪每个文档的历史记录。如果出现问题,您还可以回滚到文档的先前版本。如果您采用这样的架构,
ObjectId.getTimestamp()则您只需要使用它,并且它不依赖于 Mongoose。
ORIGINAL ANSWER:
原始答案:
If you are using ObjectId as your identity field you don't need created_atfield. ObjectIds have a method called getTimestamp().
如果您使用 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
此处的更多信息如何从 Mongo ObjectID 中提取创建日期
In order to add updated_atfiled you need to use this:
为了添加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();
});
回答by chovy
This is what I ended up doing:
这就是我最终做的:
var ItemSchema = new Schema({
name : { type: String, required: true, trim: true }
, created_at : { type: Date }
, updated_at : { type: Date }
});
ItemSchema.pre('save', function(next){
now = new Date();
this.updated_at = now;
if ( !this.created_at ) {
this.created_at = now;
}
next();
});
回答by mcompeau
Use the built-in timestampsoption for your Schema.
timestamps为您的架构使用内置选项。
var ItemSchema = new Schema({
name: { type: String, required: true, trim: true }
},
{
timestamps: true
});
This will automatically add createdAtand updatedAtfields to your schema.
这将自动添加createdAt和updatedAt领域架构。
回答by Roman Rhrn Nesterov
If use update()or findOneAndUpdate()
如果使用update()或findOneAndUpdate()
with {upsert: true}option
带{upsert: true}选项
you can use $setOnInsert
您可以使用 $setOnInsert
var update = {
updatedAt: new Date(),
$setOnInsert: {
createdAt: new Date()
}
};
回答by Phan Van Linh
Add timestampsto your Schemalike this then createdAtand updatedAtwill automatic generate for you
添加timestamps到您Schema这样便createdAt和updatedAt将自动为您生成
var UserSchema = new Schema({
email: String,
views: { type: Number, default: 0 },
status: Boolean
}, { timestamps: {} });

Also you can change createdAt -> created_atby

你也可以改变createdAt -> created_at的
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
回答by rOOb85
This is how I achieved having created and updated.
这就是我创建和更新的方式。
Inside my schema I added the created and updated like so:
在我的架构中,我添加了创建和更新的内容,如下所示:
/**
* Article Schema
*/
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
Then in my article update method inside the article controller I added:
然后在文章控制器内的文章更新方法中,我添加了:
/**
* Update a article
*/
exports.update = function(req, res) {
var article = req.article;
article = _.extend(article, req.body);
article.set("updated", Date.now());
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
};
The bold sections are the parts of interest.
粗体部分是感兴趣的部分。
回答by Nikolay_R
var ItemSchema = new Schema({
name : { type: String, required: true, trim: true }
});
ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps
回答by JohnnyHK
回答by Orr
You can use this pluginvery easily. From the docs:
您可以非常轻松地使用此插件。从文档:
var timestamps = require('mongoose-timestamp');
var UserSchema = new Schema({
username: String
});
UserSchema.plugin(timestamps);
mongoose.model('User', UserSchema);
var User = mongoose.model('User', UserSchema)
And also set the name of the fields if you wish:
如果您愿意,还可以设置字段的名称:
mongoose.plugin(timestamps, {
createdAt: 'created_at',
updatedAt: 'updated_at'
});

