将 created_at 和 updated_at 字段添加到猫鼬模式 [英] add created_at and updated_at fields to mongoose schemas
问题描述
有没有办法将 created_at 和 updated_at
字段添加到 mongoose 模式中,而不必每次调用 new MyModel()
时都将它们传递进来?
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
字段将是一个日期,并且仅在创建文档时添加.每当在文档上调用 save()
时,updated_at
字段都会更新为新日期.
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.
我已经在我的架构中尝试过这个,但是除非我明确添加它,否则该字段不会显示:
I have tried this in my schema, but the field does not show up unless I explicitly add it:
var ItemSchema = new Schema({
name : { type: String, required: true, trim: true },
created_at : { type: Date, required: true, default: Date.now }
});
推荐答案
从 Mongoose 4.0 开始,您现在可以在架构上设置时间戳选项,让 Mongoose 为您处理:
As of Mongoose 4.0 you can now set a timestamps option on the Schema to have Mongoose handle this for you:
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' } });
http://mongoosejs.com/docs/guide.html#timestamps
这篇关于将 created_at 和 updated_at 字段添加到猫鼬模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!