I have received this in postman when I try to run login route. I have used mongodb atlas and nodejs 14.17.0 version. Please help me to fix this error. This code was fond in YouTube tutorial. That code work for him but It is not working for me. { "success": false, "error": "user.matchPassword is not a function" }
Schema file
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 function This is my login router function
//------------- 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 })
}
}
Inside your Login Router function.
Just add the await keyword for finding the user with the required fields.