我正try 在我的模式上的pre‘save’挂钩中使用一个定制的加密函数,但我遇到一个错误,告诉我this.ENCRYPT不是一个函数
passwordSchema.pre('save', async function() {
if (this.isModified('password')) {
try {
this.password = this.encrypt(this.password);
} catch (error) {
throw new Error('Error while encrypting the password : ' + error.message);
}
}
if (this.isModified('login')) {
try {
this.login = passwordSchema.encrypt(this.login);
} catch (error) {
throw new Error('Error while encrypting the login : ' + error.message);
}
}
});
有一个函数Encrypt:
passwordSchema.statics.encrypt = function(password) {
const cipher = crypto.createCipheriv('aes-256-cbc', CRYPTO_AES);
let encryptedPassword = cipher.update(password, 'utf8', 'hex');
encryptedPassword += cipher.final('hex');
return encryptedPassword;
};
这里有一个模式:
const passwordSchema = new mongoose.Schema({
login: {
type: String,
required: [true, "Login required"]
},
password: {
type: String,
required: [true, "Password required"]
},
commentaire: {
type: String
}
});
注意:模式密码不会在末尾导出,而是在集合模式内使用
const collectionSchema = new mongoose.Schema(
{
[...],
passwords: [passwordSchema]
},
{
timestamps: true
}
);
我已经try 使用构造函数和其他类似于"Password.Encrypt"的东西,我可以做些什么才能在Pre‘save’钩子中使用这个静态函数?