【发布时间】:2021-04-09 14:33:22
【问题描述】:
环境:
节点 v12.19.0
mongo Atlas V4.2.11
猫鼬 V5.11.8
##############################################
我有一个用户架构
user.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
email:{
type: String,
required: true,
unique: true,
},
username:{
type: String,
required: true,
unique: true,
},
password:{
type: String,
required: true
},
profileImageUrl:{
type: String,
}
});
userSchema.pre('save', async function(next) {
try{
if(!this.isModified('password')){
return next();
}
let hashedPassword = await bcrypt.hash(this.password, 10);
this.password = hashedPassword;
return next();
} catch(err) {
return next(err);
}
});
userSchema.methods.comparePassword = async function(candidatePassword){
try{
return await bcrypt.compare(candidatePassword, this.password);
} catch(err){
throw new Error(err.message);
}
}
userSchema.set('timestamps', true);
module.exports = mongoose.model("User", userSchema);
我正在检查密码是否没有被修改,然后我在保存前修改它。
我添加了一个方法来将密码与散列密码进行比较,称为 comparePassword
我正在尝试在另一个文件中使用 comparePassword 方法
Auth.js
const db = require('../models');
const JWT = require("jsonwebtoken");
const CONFIGS = require('../config');
exports.signIn = async function(req, res, next){
try{
const user = db.User.findOne({
email: req.body.email,
});
const { id, username, profileImageUrl } = user;
const isMatch = await user.comparePassword(req.body.password) ; // here is a problem <====
if(isMatch){
const token = JWT.sign({
id,
username,
profileImageUrl,
}, CONFIGS.SECRET_KEY);
return res.status(200).json({
id,
username,
profileImageUrl,
token,
});
}
else{
return next({
status: 400,
message: "Invalid email or password",
});
}
}
catch(err){
return next(err);
}
}
当我尝试将密码与预定义的方法进行比较时,它会在响应中返回这个
user.comparePassword 不是函数
我查看了各种解决方案。
有人说这对他们有用:
userSchema.method('comparePassword' , async function(candidatePassword, next){
// the logic
})
但它不起作用我也尝试了不同的解决方案,但我不确定代码有什么问题。
更新 1:
我尝试使用静态,但它不起作用
userSchema.statics.comparePassword = async function(candidatePassword){
try{
return await bcrypt.compare(candidatePassword, this.password);
} catch(err){
throw new Error(err.message);
}
}
【问题讨论】:
-
你可以试试
statics吗? stackoverflow.com/questions/39708841/… -
是的,我尝试使用静态
标签: javascript node.js mongodb mongoose