mongoose只使用createdAt时间戳

我在mongoose中有以下消息模式:

var messageSchema = mongoose.Schema({ userID: { type: ObjectId, required: true, ref: 'User' }, text: { type: String, required: true } }, { timestamps: true }); 

有无论如何忽略updatedAt时间戳吗? 消息不会更新,所以更新将浪费空间

编辑我已经修改了答案,以反映更好的选项来使用默认的@JohnnyHK

你可以通过在模式中声明createdAt (或者你想调用它)来自己处理:

 mongoose.Schema({ created: { type: Date, default: Date.now } ... 

或者,我们也可以在预存储钩子中更新新文档的值:

 messageSchema.pre('save', function (next) { if (!this.created) this.created = new Date; next(); }) 

沿着这些线也是标志是新的 ,你可以用来检查一个文件是否是新的。

 messageSchema.pre('save', function (next) { if (this.isNew) this.created = new Date; next(); })