【发布时间】:2020-05-25 06:17:56
【问题描述】:
在将我的模型保存到 Nestjs 中的 mongoose 之前,我尝试加密一些密码并获取其盐值,但仅使用 this 引用架构本身不会产生任何结果,因为它引用了 UserSchemaProvider 对象本身,而不是我要保存的当前模型。
我的架构提供者:
export const UserSchemaProvider = {
name: 'User',
useFactory: (): mongoose.Model<User> => {
const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
birthday: { type: Date, required: true },
celphoneNumber: String,
whatsapp: Boolean,
promo: Object,
status: String
});
UserSchema.pre<User>('save', async (next) => {
const user = this;
console.log(user);
if (user.password) {
const salt = await bcrypt.genSalt();
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) return next(err);
user.password = hash;
next();
});
}
});
return UserSchema;
},
};
我的用户Module 如下:
@Module({
imports: [
MongooseModule.forFeatureAsync([
UserSchemaProvider]),
HttpModule
],
controllers: [UsersController],
providers: [UsersService, Validator, ValidationPipe, IsEmailInUseConstraint, GoogleRecaptchaV3Constraint],
})
:Nest 平台信息:
platform-express 版本:6.10.14
猫鼬版本:6.3.1
普通版本:6.10.14
核心版本:6.10.14
【问题讨论】:
标签: mongodb express mongoose nestjs