Javascript TypeError不是架构方法的函数

Javascript TypeError不是架构方法的函数,javascript,node.js,authentication,mongoose,Javascript,Node.js,Authentication,Mongoose,我目前正在开发一个平台,以磨练和发展我的技能,并试图为必要的用户注册加密密码。我想通过一个虚拟字段来实现这一点。我的问题是,我无法访问自编码的encryptPassword方法,即使我将其转换为常规函数 这是我的userSchema const mongoose = require('mongoose'); const uuidv1 = require('uuidv1'); // uuidv1(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' cons

我目前正在开发一个平台,以磨练和发展我的技能,并试图为必要的用户注册加密密码。我想通过一个虚拟字段来实现这一点。我的问题是,我无法访问自编码的
encryptPassword
方法,即使我将其转换为常规函数

这是我的
userSchema

const mongoose = require('mongoose');
const uuidv1 = require('uuidv1');
// uuidv1(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
const crypto = require('crypto');

const userSchema = new mongoose.Schema({
    name: {
        type:String,
        trim: true,
        required:true
    },
    email: {
        type:String,
        trim: true,
        required:true
    },
    hashed_password: {
        type:String,
        required:true
    },
    salt: String, 
    created : {
        type: Date,
        default: Date.now
    },
    updated: Date
});

//virtual field
userSchema.virtual('password')
.set((password) => {
    // create temporarily varibale called _password
    this._password = password;
    //generate a timestamp
    this.salt = uuidv1()
    //encryptPassword()
    this.hashed_password = this.encryptPassword(password);
})
.get(function() {
    return this._password
});

//Methods

userSchema.method = {
    encryptPassword: function(password){
        if(!password) return "";
        try {
            return  crypto.createHmac('sha1', this.salt).update(password).digest('hex');
        } catch(err) {
            return ""
        }
    }
};


module.exports = mongoose.model("User", userSchema);
所讨论的函数是
加密密码
函数。我想用
encryptPassword
功能设置哈希密码


提前感谢您的帮助

我想您在这里遗漏了一点,遗漏了函数名。您可以向架构添加如下方法:

// create methods with name
userSchema.methods.encryptPassword =  function(password){
        if(!password) return "";
        try {
            return  crypto.createHmac('sha1', this.salt).update(password).digest('hex');
        } catch(err) {
            return ""
        }
    }

有关更多详细信息,您可以检查创建实例方法的方法。

问题在于我构造该方法的方式。在使用猫鼬式的结构化方法时,它起了作用

userSchema.method({
authenticate: function(plainText){
    return this.encryptPassword(plainText) === this.hashed_password
},
encryptPassword: function(password){
    if(!password) return "";
    try {
        return  crypto.createHmac('sha1', this.salt).update(password).digest('hex');
    } catch(err) {
        return ""
    }
}
}))