【问题标题】:how to cancel mongoose query 'save' 'pre' hook如何取消猫鼬查询\'save\'\'pre\'钩子
【发布时间】:2022-11-12 00:39:31
【问题描述】:
如果使用 bcrypt 对密码进行哈希处理时出错,我想取消插入
userSchema.pre('save', async function (next) {
try {
const hashedPassWord = await bcrypt.hash(this.password, 10)
this.password = haschedpassword
} catch (err) {
// samething like rollback in sql database
}
next()
})
【问题讨论】:
标签:
javascript
node.js
mongodb
mongoose
【解决方案1】:
Erros in pre hooks
如果任何 pre hook 出错,mongoose 将不会执行后续的中间件或 hooked 函数。 Mongoose 会将错误传递给回调和/或拒绝返回的承诺。中间件报错有几种方式:
schema.pre('save', function(next) {
const err = new Error('something went wrong');
// If you call `next()` with an argument, that argument is assumed to be
// an error.
next(err);
});
schema.pre('save', function() {
// You can also return a promise that rejects
return new Promise((resolve, reject) => {
reject(new Error('something went wrong'));
});
});
schema.pre('save', function() {
// You can also throw a synchronous error
throw new Error('something went wrong');
});
schema.pre('save', async function() {
await Promise.resolve();
// You can also throw an error in an `async` function
throw new Error('something went wrong');
});
// later...
// Changes will not be persisted to MongoDB because a pre hook errored out
myDoc.save(function(err) {
console.log(err.message); // something went wrong
});
TL;博士
只需将任何内容传递给next 或抛出错误
在您的情况下,删除 try..catch 就可以了