使用猫鼬向现有模式添加验证器
Adding a validator to an existing schema with 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/#existing-documents 的本机 mongodb 节点驱动程序编写迁移。但是,似乎猫鼬实际上并没有为架构中指定的验证器添加本机 mongodb 验证器。也就是说,当我打印出集合的验证器数据时,我得到一个空对象:
// prints {}
console.log((await db.listCollections({ name: 'users' }).toArray())[0].options.validator);
我不想添加这个新的验证器,使其不同于我在架构上的现有验证器。
实际上,这看起来根本不是问题,因为我认为猫鼬没有使用 mongodb 本机验证器,因此不需要对实际数据库进行任何更改。 Mongoose 将像这样自动获取验证器更改,无需迁移。
起初我并不清楚这一点,因为我试图使用 mongoose.model
函数手动重新创建模型,但在覆盖现有模型时出现错误。
我有一个如下所示的猫鼬模式:
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/#existing-documents 的本机 mongodb 节点驱动程序编写迁移。但是,似乎猫鼬实际上并没有为架构中指定的验证器添加本机 mongodb 验证器。也就是说,当我打印出集合的验证器数据时,我得到一个空对象:
// prints {}
console.log((await db.listCollections({ name: 'users' }).toArray())[0].options.validator);
我不想添加这个新的验证器,使其不同于我在架构上的现有验证器。
实际上,这看起来根本不是问题,因为我认为猫鼬没有使用 mongodb 本机验证器,因此不需要对实际数据库进行任何更改。 Mongoose 将像这样自动获取验证器更改,无需迁移。
起初我并不清楚这一点,因为我试图使用 mongoose.model
函数手动重新创建模型,但在覆盖现有模型时出现错误。