【发布时间】:2018-10-26 02:34:27
【问题描述】:
我的用户模型中有以下预验证钩子:
UserSchema.pre<IUser>('validate', async function (next: NextFunction): Promise<void> {
if (!this.isModified('password')) {
return next()
}
if (this.password.length < 8) {
this.invalidate(
'password',
'Invalid password ...',
''
)
console.log(this.password)
}
this.password = await bcrypt.hash(this.password, 12)
})
架构是:
const UserSchema: mongoose.Schema = new mongoose.Schema({
login: {
required: true,
type: String,
unique: 'Le nom d\'utilisateur `{VALUE}` est déjà utilisé'
},
mail: {
required: true,
type: String,
unique: 'Le mail `{VALUE}` est déjà utilisé'
},
password: { required: true, type: String, /*select: false*/ },
// In test env auto validate users
isVerified: { type: Boolean, default: config.env !== 'test' ? false : true },
profilPic: { type: mongoose.Schema.Types.ObjectId, ref: 'Image' },
}, { timestamps: true })
但是在做的时候
try {
await User.create({ login: 'user2', mail: 'user1@mail.com', password: '123' })
} catch (error) {
console.log(error)
}
我有日志123,这表明代码进入了 pre hook 中的第二个if,但由于日志在this.invalidate 之后,我不明白为什么没有抛出错误。
我在其他一些模型中成功使用了相同的钩子,操作更复杂,没有错误。
我真的不明白为什么这个不起作用
【问题讨论】:
标签: javascript node.js mongoose async-await mongoose-schema