簡體   English   中英

TypeError 不是 Schema 方法的 function

[英]TypeError not a function for a Schema method

我目前正在開發一個平台,以磨練和發展我的技能,並嘗試加密密碼以進行必要的用戶注冊。 我想通過一個虛擬字段來做到這一點。 我的問題是,即使我把它變成一個普通的 function,我也無法訪問自編碼的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);

有問題的 function 是encryptPassword function。 我想用encryptPassword function 設置hashed_password ssword。

在此先感謝您的幫助

我認為您在這里缺少一件,缺少 function 名稱。 您可以像這樣向架構添加方法:

// 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 ""
        }
    }

有關更多詳細信息,您可以查看mongoose 文檔以創建實例方法。

問題在於我構建該方法的方式。 在使用 mongoose 的結構化方法時,它起作用了。

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 ""
    }
}

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM