node.js - 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 是其中的方法!
我只需要 isValidPassword 方法中的那个布尔值
感谢您的关注。
解决方案
好吧,我解决了,这是一个愚蠢的错误..问题就在这里
const user = User.findOne({email});
我忘了把await放在前面User.findOne(...)
所以基本上它不会等待来自数据库的响应,它会返回一个空的用户对象。
推荐阅读
- memory - 在 Lua 中,垃圾收集器可以确定性管理的对象/表的数量是否有限制?
- python - 将 3 维 Numpy 数组转换为 4 维 Numpy 数组
- javascript - 在由命令的发送者确定的通道中发送消息
- python - 有人可以教我如何使我的代码更好以及如何修复错误和错误吗?
- c - 如何将具有指数和 sin 函数的方程转换为 C?
- python - Python中从一个坐标系到另一个坐标系的图像转换
- laravel-livewire - Livewire AppServiceProvider 启动方法未在更新时执行
- c# - 为什么大数组可以同步到小数组?
- node.js - 来自 MongoDB 的 React Native fetch 不起作用
- python - 在 Python 上堆叠两个图像以获得单个图像