Rit*_*ika 6 schema mongoose mongodb node.js
我的架构如下所示:
const UserSchema = Schema({
_id: mongoose.Schema.Types.ObjectId,
userName: {
type: String,
required: true,
},
userPhoneNumber: {
type: String,
},
role:[{
type:mongoose.Schema.Types.ObjectId,
ref:Role
}]
});
Run Code Online (Sandbox Code Playgroud)
通过这个模式,我在数据库中添加了文档role:[]
。但现在根据要求,我需要更新架构而不删除现有集合。我需要更新数据,除了角色之外,所有字段都相同。我想将现有记录更新为角色
const UserSchema = Schema({
_id: mongoose.Schema.Types.ObjectId,
userName: {
type: String,
required: true,
},
userPhoneNumber: {
type: String,
},
role:[{
type:mongoose.Schema.Types.ObjectId,
ref:Role
}]
});
Run Code Online (Sandbox Code Playgroud)
那么如何在不删除集合的情况下更新架构。
MongoDB 是为了解决这种类型的模式问题而生的,你唯一需要做的就是添加另一个具有默认值的字段,就像这样
旧架构:
new Schema({
name: { type: string }
})
Run Code Online (Sandbox Code Playgroud)
带有出生地字段的新架构:
new Schema({
name: { type: string },
birthplace: { type: string, required: true, default: 'neverborn' }
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1603 次 |
最近记录: |