如果模式在 Mongoose 中发生更改,如何使用默认值更新集合中的所有文档

How to update all the documents in a collection with the default values if Schema got changed in Mongoose

我之前有过这样的架构

var schema = mongoose.Schema({
    type: String,
    name: String,
});

现在我的 Schema 已经改变了

var schema = mongoose.Schema({
    type: String,
    name: String,
    content: {
        title: {type: String, default: 'Some Title'},
        description: {type: String, default: 'Some Description'}
    }
});

既然架构已经改变,我想用默认值更新集合中以前的文档,怎么办?

直接在 MongoDB shell

上执行以下 updateMany 查询
db.collectionName.updateMany({}, {$set: {
    content: {title: "Some title", description: "Some description"}
}})

要更新的第一个参数是一个空对象,它匹配所有现有记录。