我正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’钩子中使用这个静态函数?

推荐答案

statics%用于在模型上生成静态方法.
您应该try 使用methods来定义实例函数:

passwordSchema.methods.encrypt = function(password) { ... }

Javascript相关问答推荐

React Hooks中useState的同步问题

如何通过在提交时工作的函数显示dom元素?

成帧器运动中的运动组件为何以收件箱开始?

TypScript界面中的Infer React子props

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

InDesign—创建一个独立的窗口,在文档中进行更正时保持打开状态

D3 Scale在v6中工作,但在v7中不工作

Chart.js-显示值应该在其中的引用区域

将核心模块导入另一个组件模块时存在多个主题

如何在Angular拖放组件中同步数组?

第一项杀死下一项,直到数组长度在javascript中等于1

FileReader()不能处理Firefox和GiB文件

如何使用画布在另一个内部绘制一个较小但相同的形状,同时保持恒定的边界厚度?

使用RxJS from Event和@ViewChild vs KeyUp事件和RxJS主题更改输入字段值

AG-GRIDreact 显示布尔值而不是复选框

如何在加载页面时使锚定标记成为焦点

使用Java脚本在div中创建新的span标记

如何缩小函数中联合返回类型的范围

:host::ng-Deep不将样式应用于material 复选框

单击时同时 Select 和展开可访问的行