提问者:小点点

如何使用Mongoose在mongoDB中手动设置createdAt时间戳?


我正在尝试迁移我的数据库,方法是将时间戳添加到先前丢失时间戳的所有行中。我使用_id计算了createdAt timestamp,但我无法设置时间戳。我在这里做错了什么?有人能帮忙吗?

    let Question = db.model('Question');

    let items = await Question.findWithDeleted();

    let processedIds = items.map((q) => q._id);
    processedIds.forEach(function (id) {

        const timestamp = id.getTimestamp();

        // const date = new Date(parseInt(timestamp, 16) * 1000);
        // echo(timestamp)
        Question.update({ "_id": id }, { "$set": { createdAt: timestamp } }, (h) => {
            console.log(h);
        });

    });

下面是模型:


    const Question = new Schema({
        "type": {
            type: String,
            trim: true,
            enum: Object.values(questionTypes),
            required: 'Question type is required'
        },
        "text": {
            type: String,
            required: true
        },
        "desc": NotRequiredStringSchema,
        "options": [{
            "id": ObjectId,
            "name": NotRequiredStringSchema,
            "helperText": NotRequiredStringSchema,
            "icon_key": NotRequiredStringSchema,
            "icon_url": NotRequiredStringSchema,
            "icon_svg": NotRequiredStringSchema
        }],
        "placeHolder": NotRequiredStringSchema,
        "buttonPosition": NotRequiredStringSchema,
        "buttonText": NotRequiredStringSchema,
        "buttonHoverText": NotRequiredStringSchema,
        "helperText": NotRequiredStringSchema,
        "max": Number,
        "min": Number,
        "default": Mixed,
        "icon_key": NotRequiredStringSchema,
        "icon_url": NotRequiredStringSchema,
        "icon_svg": NotRequiredStringSchema,
        "showTick": { type: Boolean, required: false, default: false },
        "lang": {
            required: true,
            type: Map,
            of: {
                type: Map,
                of: String
            }
        }
    }, {
            timestamps: true
        });


共2个答案

匿名用户

如果您像这样设置模式

const SchemaName = new Schema({
 .......
}, {
  timestamps: true
})

它将自动创建createdAt和updatedAt字段,并在每次执行create和update操作时更新它们的值。

其他情况下,如果您手动创建createdAt和updatedAt字段,就像这个模式

const SchemaName = new Schema({
 .......
 createdAt: { type: Date, default: Date.now },
 updatedAt: { type: Date, default: Date.now }
})

然后可以使用中间件在创建和更新记录时更新createdAt和updatedAt值。

SchemaName.post('save', (doc) => {
  console.log('%s has been saved', doc._id);
});

SchemaName.pre('update', () => {
  this.update({},{ $set: { updatedAt: new Date() } });
});

匿名用户

问题是您的模式不包含createdAt字段,mongoose默认情况下保存数据时启用了strict选项,如果您的模式不包含字段,则无法向it文档添加新字段。因此,您首先需要将createdAt字段添加到您的模式中,下面只是一个示例。

 createdAt: {type: Date, default: Date.now}

在将此字段添加为字段之后,您的查询应该不会出现问题。