[英]Adding a validator to an existing schema with mongoose
我有一个看起来像这样的 mongoose 架构:
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
minlength: 4,
maxlength: 20,
validate: {
validator: username => !username.startsWith('banned_prefix')
msg: 'This username is invalid',
type: 'username-validation-1'
}
}
});
我希望架构看起来像这样:
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
minlength: 4,
maxlength: 20,
validate: [
{
validator: username => !username.startsWith('banned_prefix')
msg: 'This username is invalid',
type: 'username-validation-1'
},
{
validator: username => !username.startsWith('new_banned_prefix')
msg: 'This username is invalid',
type: 'username-validation-2'
}
]
}
});
鉴于数据库和架构已经存在并且我不想完全删除和重置数据库,我该怎么做?
我尝试使用基于https://docs.mongodb.com/manual/core/schema-validation/#exist的本机 mongodb 节点驱动程序编写迁移。 但是,似乎 mongoose 实际上并未为架构中指定的验证器添加本机 mongodb 验证器。 也就是说,当我打印出集合的验证器数据时,我得到一个空的 object:
// prints {}
console.log((await db.listCollections({ name: 'users' }).toArray())[0].options.validator);
我不想添加这个新的验证器,使其不同于我在架构上拥有的现有验证器。
实际上,这看起来根本不是问题,因为我认为 mongoose 没有使用 mongodb 本机验证器,因此不需要对实际数据库进行任何更改。 ZCCADCDEDB567ABAE643E15DCF0974E503Z 将自动获取这样的验证器更改,无需迁移。
This wasn't clear to me at first because I was trying to manually recreate the model with the mongoose.model
function and was getting errors about overwriting an existing model.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.