将created_at和updated_at字段添加到mongoose模式 [英] add created_at and updated_at fields to mongoose schemas

查看:110
本文介绍了将created_at和updated_at字段添加到mongoose模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将created_at和updated_at字段添加到一个mongoose模式,而不必在每次调用新的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 expcitly add it:

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


推荐答案

如果使用 update findOneAndUpdate()

{upsert:true您可以使用 $ setOnInsert


var update = {
  updatedAt: new Date(),
  $setOnInsert: {
    createdAt: new Date()
  }
};

这篇关于将created_at和updated_at字段添加到mongoose模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆