猫鼬在预验证钩子中失效不会引发错误



>我的用户模型中有以下预验证钩子:

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之后,我不明白为什么没有抛出错误。

我成功地在其他一些具有更复杂的操作的模型中使用了相同的钩子,没有错误。

我真的不明白为什么这个不起作用

这种行为的背景是Document.prototype.invalidate()不会引发错误 - 它会返回错误。为了阻止当前中间件链的执行,您需要调用next并传递此错误:

if (this.password.length < 8) {
const validationError = this.invalidate(
'password',
'Invalid password ...',
''
);
next(validationError);
console.log(this.password); // Won't run
}

throw它:

if (this.password.length < 8) {
const validationError = this.invalidate(
'password',
'Invalid password ...',
''
);
throw validationError;
console.log(this.password); // Won't run
}

Mongoose 中间件文档未将 create 列为受支持的操作。你试过保存吗?

最新更新