如何使用mongoose手动设置mongoDB中的createdAt时间戳?

4

我正在尝试通过为所有之前缺少时间戳的行添加时间戳来迁移我的数据库。我已经使用_id计算出了createdAt时间戳,但是我无法设置时间戳。我在这里做错了什么?有人可以帮忙吗?

    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: '问题类型必填'
        },
        "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
        });

你能发布模式吗? - Kalana Demel
你现在可以检查一下吗,@KalanaDemel? - Abhinav Jain
您想在现有记录或新创建/更新的记录上添加时间戳吗? - Ashok
@Abhinav Jain,请检查该解决方案是否有所帮助。 - Kalana Demel
2个回答

8
如果您将架构设置为如下形式:
const SchemaName = new Schema({
 .......
}, {
  timestamps: true
})

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

如果您手动创建像这个模式中的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() } });
});

0
问题在于您的模式中没有包含createdAt字段。Mongoose默认启用严格选项保存数据,如果您的模式不包含某个字段,则无法向其添加新字段Docs。因此,您首先需要将createdAt字段添加到模式中,以下是一个示例。
 createdAt: {type: Date, default: Date.now}

在将此作为字段添加后,您的查询应该可以正常工作。

我有时间戳:true,所以它应该有那些字段,对吗? 但是这个解决方案没有起作用。 - Abhinav Jain
哦,我没有看到标志,但很高兴它对你有用 :D - Kalana Demel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接