Я пытаюсь зашифровать некоторые пароли и получить их соль перед сохранением моей модели в mongoose в Nestjs, но простое использование this
для ссылки на саму схему не дает никаких результатов, так как относится к UserSchemaProvider
объекту 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:
платформа-экспресс версия: 6.10.14
версия мангуста: 6.3.1
общая версия: 6.10.14
основная версия: 6.10.14
Всего 1 ответ
Ваш обработчик pre
hook не должен быть arrow function () => {}
. mongoose
обработчика mongoose
должен быть контекст выполнения, указывающий на текущий сохраняемый document
. При использовании arrow function
ваш контекст выполнения pre
hook больше не является документом, следовательно, this
внутри обработчика больше не сам документ.
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 function(next) { // <-- change to a function instead
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;
},
};