首页 > 解决方案 > user.isValidPassword 不是函数

问题描述

我是 node.js 和 mongodb 的新手,我正在使用 passport.js 开发身份验证 api。我在用户模型中有一个名为“isValidPassword”的方法,但我不能在护照本地策略中使用它来登录。

我总是有“user.isValidPassword 不是函数”

这是用户模型


    const mongoose = require ('mongoose');
    const bcrypt = require('bcryptjs'); 
    const Schema = mongoose.Schema;

    // Create Schema
    const  userSchema = new Schema({
        email: String,
        password: {
            type: String,
            required: true,
            minlength: 4,
        id_user: Number,
        username: String,
        nom: String,
        prenom: String,
        num_portable: Number,
        num_fix: Number,
        image: String
        }

    });

    // Hash password before saving the user
    userSchema.pre('save', async function (next){
        try {
            // Generate Salt for the password encryption
            const salt = await bcrypt.genSalt(15);
            // Generate a hashed password using Salt
            const passwordHash = await bcrypt.hash(this.password, salt);
            // Re-assign the hashed password to the user's acuatl password
            this.password = passwordHash;
            next();
            console.log ('Salt: '+ salt);
            console.log ('Original password: ' + this.password);
            console.log ('Hashed Password: ' +passwordHash);
        } catch (error) {
            next(error);
        }
    });
    // isValidPassword
    // Compare hashedpassword vs password stored in db
    userSchema.methods.isValidPassword  = async function(newPassword) {
        try {
            return await bcrypt.compare(newPassword, this.password);
        } catch (error) {
            throw new Error (error);
        }
    }
    // Create Module
    const User = mongoose.model('user',userSchema);
    // Export Module
    module.exports = User;

这是我在护照​​本地策略中使用它的时候

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async(email, password, done)=> {
    try {
        // Find user by the given email
        const user = User.findOne({email});
        // If the user doesn't existe, handle it
        if(!user){
            return done(null, false);
        }
        // else, check if the password is correct

        const isMatch = await user.isValidPassword(password);
        // if the password is wrong, handle it
        if(!isMatch){
            return done(null, false);
        }
        done(null, user);
    } catch (error) {
        done(error, false);
    }

}));

当我尝试执行“console.log(user)”时,我发现 isValidPassword 是其中的方法! https://i.stack.imgur.com/guIdu.png

我只需要 isValidPassword 方法中的那个布尔值

感谢您的关注。

标签: node.jsmongodbpassport.js

解决方案


好吧,我解决了,这是一个愚蠢的错误..问题就在这里

const user = User.findOne({email});

我忘了把await放在前面User.findOne(...)所以基本上它不会等待来自数据库的响应,它会返回一个空的用户对象。


推荐阅读