【发布时间】:2020-12-17 20:39:12
【问题描述】:
我在我的 node.js 中使用猫鼬 - 快递。在我的模式模型中,我使用包mongoose-unique-validator 来检查用户电子邮件是否唯一,如果电子邮件已经存在,我会收到错误ValidationError: User validation failed: email: Error, expected "email" to be unique. Value: "example@example.com"(这很好)。我决定以这种方式将我的承诺从猫鼬变成rxjs observables:
controller.ts
creatUser(req: Request, res: Response, next: NextFunction) {
from(bcrypt.hash(req.body.password, 10))
.pipe(
mergeMap((hash) => {
const avatartPath = this.utilities.generateImgPath(req);
const user = this.userAdatper.userAdatper(req.body, { password: hash, avatar: avatartPath });
return of(new User(user).save()).pipe(catchError((error) => of(error)));
})
)
.subscribe(
(user) => {
console.log() // Promise is resolve here on the validation error return an empty object
res.status(201).send(user);
},
(err) => {
console.log(err);
res.status(500);
const error = new Error(`Internal Server Error - ${req.originalUrl}`);
next(error);
}
);
}
**Schema**
const UserSchema = new Schema({
user_rol: {
type: String,
default: 'subscriber',
},
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
requiered: true,
},
fullName: {
type: String,
requiered: true,
},
email: {
type: String,
requiered: true,
unique: true,
},
password: {
type: String,
requiered: true,
},
avatar: {
type: String,
requiered: true,
},
favorites: [
{
type: [Schema.Types.ObjectId],
ref: 'ArcadeItems',
},
],
updatedOn: {
type: Date,
required: true,
},
created: {
type: Date,
default: Date.now,
},
});
UserSchema.plugin(uniqueValidator);
但由于某种原因,如果promise失败,它会在订阅返回后成功回调并且清空对象并且没有错误回调时解决,尝试从rxjs操作符实现catchError()但没有成功。
【问题讨论】:
-
有什么问题?
bcrypt.hash没有失败? -
如果我插入和电子邮件已经在 db
new User(user).save()上,插件mongoose-unique-validator会抛出错误,我会尝试在pipe或订阅错误中捕获错误回调但由于某种原因 observable 成功完成。 -
你
catchError并返回一个成功的流,所以这和预期的一样?另外,当你的意思是“an”时,你一直在输入“and”——这是故意的吗?这很混乱。 -
我找到了原因,我将
of(new User(user).save())替换为from(new User(user).save())以保证对 observables 的承诺from()是正确的运算符 -
catchError(err => of(err))将错误流转换为成功的流,将错误作为对象发送到观察者的.next回调。
标签: node.js mongodb mongoose rxjs