1

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.

Neil Lunn
  • 130,590
  • 33
  • 275
  • 280
Toan Tran
  • 1,552
  • 1
  • 19
  • 36
  • 1
    Don't use arrow functions. The `this` context in these methods is taken in context of the model instance when that is created, rather than in composition of the schema. If you use the regular `function()` syntax, then you will not have the problem – Neil Lunn Jun 08 '17 at 10:51
  • @NeilLunn Thank you for commenting here. Do you know any way to make it work with arrow function? I'm trying to learn ES6, so I'd lie to use ES6 syntax, something like arrow function. – Toan Tran Jun 08 '17 at 10:57
  • The point is that it **cannot** work. The reason is that basically what you are writing here is more like *'declaring a variable as a function"* which is going to be attached to the model instance when created. This is an old JavaScript trick, and a case where arrow functions do not apply since we actually want `this` to refer to the generated instance. – Neil Lunn Jun 08 '17 at 11:07

0 Answers0