是否有一种方法可以将created_at和updated_at字段添加到猫鼬模式中,而不必在每次调用new MyModel()时传递它们?

created_at字段将是一个日期,仅在创建文档时添加。 每当对文档调用save()时,updated_at字段将被更新为新的日期。

我已经在我的模式中尝试了这一点,但除非我显式地添加它,否则字段不会显示:

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

当前回答

var ItemSchema = new Schema({
    name : { type: String, required: true, trim: true }
});

ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps

文档:https://mongoosejs.com/docs/guide.html时间戳

其他回答

如果使用update()或findOneAndUpdate()

带有{upsert: true}选项

你可以使用$setOnInsert

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

为您的模式使用内置的时间戳选项。

var ItemSchema = new Schema({
    name: { type: String, required: true, trim: true }
},
{
    timestamps: true
});

这将自动将createdAt和updatedAt字段添加到模式中。

http://mongoosejs.com/docs/guide.html#timestamps

从Mongoose 4.0开始,你现在可以在Schema上设置一个时间戳选项,让Mongoose为你处理这个问题:

var thingSchema = new Schema({..}, { timestamps: true });

你可以像这样更改字段的名称:

var thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });

http://mongoosejs.com/docs/guide.html#timestamps

像这样向Schema添加时间戳,然后createdAt和updatedAt将自动为您生成

var UserSchema = new Schema({
    email: String,
    views: { type: Number, default: 0 },
    status: Boolean
}, { timestamps: {} });

你也可以改变createdAt -> created_at by

timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }

使用函数返回计算出的默认值:

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

ItemSchema.pre('save', function(done) {
  this.updated_at = Date.now();
  done();
});