我有以下长的模式:
const mySchema = new mongoose.Schema({
// some stuff, firstName, lastName ... etc
password: {
type: String,
minLength: 8,
maxLength: 120,
}
})
并且我在其中一个路由中,我只想在密码文件上运行验证。我可以在Mongoose中做一些事情吗?例如:
mySchema.fields.password.validate("123") // Error: password is less than 8 characters!
有这样的东西吗?
Mongoose的维护者在这里回答了这个问题
mySchema.path("密码")。doValidate(价值,fn)。或者你可以doc.validate(['密码']).
使用猫鼬自定义验证器https://mongoosejs.com/docs/validation.html定制验证器
,
const mySchema = new mongoose.Schema({
// some stuff, firstName, lastName ... etc
password: {
type: String,
minLength: 8,
maxLength: 120,
validate: {
validator: function (v) {
//do something, return false if something wrong
return /^[A-Za-z0-9_]+$/.test(v);
}
}
}
})