类型错误:user.authenticate 不是函数

问题描述

我正在尝试使用架构方法实现登录方法,但每次都出现错误

我的用户模型代码

const mongoose = require("mongoose")
const uuidv1 = require("uuidv1")
const crypto = require('crypto');
const userSchema = new mongoose.Schema({
name: {
    type: String,trim: true,},email: {
    type: String,hashed_password: {
    type: String,salt: String,created: {

    type: Date,default: Date.Now
},updated: {
    type: Date
}

})


userSchema.virtual('password')
   .set(function(password) {
    //create temporary variable called _password
     this._password = password;
    //generate a timestamp 
    this.salt =uuidv1();
    // encrypt password()
    this.hashed_password =this.encryptPassword(password);
    })

    .get(function() {
       return this._password;
     });

userSchema.methods = {

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


   module.exports = mongoose.model("user",userSchema);

并且我在以下代码中导出上述文件的身份验证功能

const jwt = require('jsonwebtoken');
const user = require('../models/user');
require('dotenv').config();

exports.signup = async(req,res ) => {
   const userExists = await User.findOne({email: req.body.email})

 if(userExists) return res.status(403).json({
    error: "Email is already taken"
  })
 const user = await new User(req.body)
 await user.save()
 res.status(200).json({user});
 };


 exports.signin =(req,res) => {
//find the user based on email
const {email,password} = req.body
user.findOne({email},() => {
    if(!user){
        return res.status(401).json({
            error: "User does not exist. Please signin."
        })
    }
    
    //created the model for aunthentication and use here
    if(!user.authenticate(password)){
        return res.status(401).json({
            error: "Email and password do not match"
        })
    }
    
    //generate a token with user id and secret
    const token = jwt.sign({_id: user._id},process.env.JWT_SECRET)
    
    //persist the token as 't' in cookie to frontend client
    res.cookie('t',token,{expire:new Date() + 9999})
    //return response with user and token to frontend client
    const{_id,name,email} = user
    return res.json({token,user: {_id,email,name}})
})

 }

我得到了错误
扔er; // 未处理的“错误”事件。

TypeError: user.authenticate 不是函数

请帮忙

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)