当我尝试在邮递员" { "success": false, "error": "user.matchPassword is not a function"

时间:2021-07-01 18:51:47

标签: mongodb model postman router login-script

当我尝试运行登录路由时,我在邮递员那里收到了这个。我用过 mongodb atlas 和 nodejs 14.17.0 版本。请帮我解决这个错误。这段代码在 YouTube 教程中很受欢迎。该代码对他有用,但对我不起作用。 { “成功”:错误, “错误”:“user.matchPassword 不是函数” }

架构文件

const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
//-------------------------------------------------------------------------------------

//------------- User Schema -------------
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, 'Please provide username'],
  },
  email: {
    type: String,
    required: [true, 'Please provide email address'],
    unique: true,
  
  },
  password: {
    type: String,
    required: [true, 'Please add a password'],
    minlength: 6,
    select: false,
  },
  resetPasswordToken: String,
  resetPasswordExpire: Date,
})

//------------- password encription before saving the schema  -------------
UserSchema.pre('save', async function (next) {
  if (!this.isModified('password')) {
    next()
  }

  const salt = await bcrypt.genSalt(10)
  this.password = await bcrypt.hash(this.password, salt)
  next()
})

//------------- password checking for login  -------------
UserSchema.methods.matchPassword = async function (password) {
  return await bcrypt.compare(password, this.password)
}

const User = mongoose.model('User', UserSchema)

module.exports = User

Loginrouter 功能 这是我的登录路由器功能

//------------- Login route -------------
exports.login = async (req, res, next) => {
  const { email, password } = req.body

  if (!email || !password) {
    res
      .status(400)
      .json({ success: false, error: 'Please provide email and paswword.' })
  }
  try {
    const user = User.findOne({ email }).select('+password')
    if (!user) {
      res.status(404).json({ success: false, error: 'Invalid credentials.' })
    }

    const isMatch = await user.matchPassword(password)

    if (!isMatch) {
      res.status(404).json({ success: false, error: 'Invalid credentials' })
    }

    res.status(200).json({ success: true, token: '12646dfsdhf' })
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }

}

0 个答案:

没有答案