mongodb自動生成createdAt和updatedAt兩個欄位
阿新 • • 發佈:2019-02-01
雖然我們可以在文件建立的時候插入建立時間欄位createAt,但是文件更新的時間updateAt是不能直接更新的。而且我們也不可能在寫入操作中每次都更新這個欄位。幸好,在Mongoose Schemas定義中給我們提供了timestamps選項。
官方文件介紹:https://mongoosejs.com/docs/guide.html#timestamps
If set timestamps, mongoose assigns
createdAt
andupdatedAt
fields to your schema, the type assigned isDate
.
By default, the name of two fields are createdAt and updatedAt, customize the field name by setting timestamps.createdAt and timestamps.updatedAt.
//預設定義Schema設定
//var thingSchema = new Schema({..}, { timestamps: true });
//生成的欄位預設為updatedAt, createdAt
//也可以自己定義名稱
var thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing();
thing.save(); // `created_at` & `updatedAt` will be included