我在node.js express中使用mongose。在我的模式模型中,我使用了包
mongoose-unique-validator
要检查用户电子邮件是否唯一,如果电子邮件已经存在,我将收到并出错
ValidationError: User validation failed: email: Error, expected "email" to be unique. Value: "example@example.com"
(这很好)。我决定把我的承诺从猫鼬变成
rxjs observables
这种方式:
控制器.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失败,它会在订阅返回后解析成功回调,并解析空对象而不解析错误回调,尝试实现
catchError()
来自rxjs运营商,但没有成功。