提问者:小点点

向已创建的文档添加日期类型


我的猫鼬模式定义如下。

mongoose.Schema({
    "url": String,
    "translations": [
        {
            "targetLang": String,
            "source": String,
            "target": String
        }
    ],
}, { versionKey: false });

我更新了架构以包含createdatupdatedat,新架构如下:

mongoose.Schema({
    "url": String,
    "translations": [
        {
            "targetLang": String,
            "source": String,
            "target": String,
            "createdAt": { type: Date, default: Date.now },
            "updatedAt": { type: Date, default: Date.now }
        }
    ],
}, { versionKey: false });

因此,当创建新文档时,会自动填充createdatupdatedat。如何使具有新键的旧文档在处创建和处更新。有什么办法吗?

注意:我同意旧文件有当前或任何以前的日期。但我想让他们都有个约会。


共1个答案

匿名用户

您需要手动更新它们,例如从mongoshell:

{
    const toUpdate = db.getCollection('collection').find({
        $or: [
            { 'translations.createdAt': null },
            { 'translations.updatedAt': null }
        ]
    });

    toUpdate.forEach(doc => {
        const timestamp = doc._id.getTimestamp();
        doc.translations.createdAt = timestamp;
        doc.translations.updatedAt = timestamp;
        
        db.getCollection('collection').updateOne({ _id: doc._id }, { $set: doc });
    });
}