This question already has an answer here:
I am developing Node.js application with ES6.
Using bcrypt-nodejs to encrypt and decrypt password before saving to MongoDB.
There is Schema defination:
import mongoose from 'mongoose'
import bcrypt from 'bcrypt-nodejs'
const Schema = mongoose.Schema
let userSchema = new Schema({
username: {
type: String,
min: 6,
max: 20,
unique: true,
required: true,
dropDups: true
},
password: {
type: String,
min: 6,
max: 20
}
})
// generate password hash
userSchema.methods.generateHash = password => bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
// checking if password is valid
userSchema.methods.validPassword = password => bcrypt.compareSync(password, this.password)
export default mongoose.model('User', userSchema)
When I want to verify user password I call below function:
if (!user.validPassword(req.body.password)) {
console.error(`Authentication failed. Wroong password for user '${req.body.username}'`)
}
Then the error occurred:
events.js:182
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'password' of undefined
I think this problem is caused by ES6 syntax
, this
is undefined. But I don't know how I can fix it.
Thank you all in advance.
via Toan Tran
No comments:
Post a Comment