【问题标题】:I have got this error when I try to make post request in postman " { "success": false, "error": "user.matchPassword is not a function" }当我尝试在邮递员“{“成功”:假,“错误”:“user.matchPassword不是函数”}中发出帖子请求时出现此错误
【发布时间】:2022-02-14 02:06:10
【问题描述】:

当我尝试运行登录路由时,我在邮递员中收到了这个。我用过 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

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

//------------- 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 })
  }

}

【问题讨论】:

    标签: mongodb model postman router login-script


    【解决方案1】:

    在您的登录路由器函数中。

    try {
        const user = await User.findOne({ email }).select('+password')
    }
    

    只需添加 await 关键字即可使用必填字段查找用户。

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 2020-06-07
      • 2022-07-19
      • 2021-05-18
      • 1970-01-01
      • 2019-12-09
      • 2019-09-08
      • 1970-01-01
      • 2022-09-23
      相关资源
      最近更新 更多