【问题标题】:Update schema without dropping collection in mongodb更新模式而不删除 mongodb 中的集合
【发布时间】:2020-11-29 09:57:48
【问题描述】:

我的架构看起来像:

const UserSchema = Schema({
    _id: mongoose.Schema.Types.ObjectId,
    userName: {
        type: String,
        required: true,
    },
    userPhoneNumber: {
        type: String,
    },
    role:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:Role
    }]
});

使用此架构,我在 DB 中添加了带有 role:[] 的文档。但现在根据要求,我需要在不删除现有集合的情况下更新架构。我需要更新数据,所有字段都相同,除了角色。我想用角色更新现有记录

role:[{
    department:{
        type:string
    },
    roleNames:[{
        type:type: mongoose.Schema.Types.ObjectId,
        ref:Role
    }]
}]

那么如何在不删除集合的情况下更新架构。

【问题讨论】:

标签: node.js mongodb mongoose schema


【解决方案1】:

MongoDB 就是为解决这种类型的模式问题而生的,您只需添加另一个具有默认值的字段 就这样

旧架构:

new Schema({
    name: { type: string }
})

带有出生地字段的新架构:

new Schema({
    name: { type: string },
    birthplace: { type: string, required: true, default: 'neverborn' }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-23
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多