是否有一种方法可以将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 }
});

当前回答

如果你使用nestjs和@Schema装饰器,你可以实现这样的效果:

@Schema({
  timestamps: true,
})

时间戳选项告诉猫鼬将createdAt和updatedAt字段分配给你的模式。分配的类型是Date。

默认情况下,字段的名称是createdAt和updatedAt。

通过设置时间戳自定义字段名。createdAt和timestamp . updatedat。

其他回答

在您的模型模式中,只需添加一个属性时间戳,并为其赋值为true,如下所示

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

这就是我创造和更新的方式。

在我的模式中,我像这样添加了创建和更新:

   /**
     * Article Schema
     */
    var ArticleSchema = new Schema({
        created: {
            type: Date,
            default: Date.now
        },
        updated: {
            type: Date,
            default: Date.now
        },
        title: {
            type: String,
            default: '',
            trim: true,
            required: 'Title cannot be blank'
        },
        content: {
            type: String,
            default: '',
            trim: true
        },
        user: {
            type: Schema.ObjectId,
            ref: 'User'
        }
    });

然后在文章控制器内的文章更新方法中添加:

/**
     * Update a article
     */
    exports.update = function(req, res) {
        var article = req.article;

        article = _.extend(article, req.body);
        article.set("updated", Date.now());

        article.save(function(err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.json(article);
            }
        });
    };

粗体部分是我们感兴趣的部分。

const mongoose = require('mongoose');
const config = require('config');
const util = require('util');

const Schema = mongoose.Schema;
const BaseSchema = function(obj, options) {
  if (typeof(options) == 'undefined') {
    options = {};
  }
  if (typeof(options['timestamps']) == 'undefined') {
    options['timestamps'] = true;
  }

  Schema.apply(this, [obj, options]);
};
util.inherits(BaseSchema, Schema);

var testSchema = new BaseSchema({
  jsonObject: { type: Object }
  , stringVar : { type: String }
});

现在您可以使用这个选项,这样就不需要在每个表中都包含这个选项

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

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

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

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

如果使用update()或findOneAndUpdate()

带有{upsert: true}选项

你可以使用$setOnInsert

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