我的猫鼬模式定义如下。
mongoose.Schema({
"url": String,
"translations": [
{
"targetLang": String,
"source": String,
"target": String
}
],
}, { versionKey: false });
我更新了架构以包含createdat
和updatedat
,新架构如下:
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 });
因此,当创建新文档时,会自动填充createdat
和updatedat
。如何使具有新键的旧文档在
处创建和在
处更新。有什么办法吗?
注意:我同意旧文件有当前或任何以前的日期。但我想让他们都有个约会。
您需要手动更新它们,例如从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 });
});
}