Tuesday, 16 May 2017

"this" keyword in sequelize does not refer to the current instance

I create a User model like this and I want to write a function to update user's password updatePassword():

"use strict";
var bcrypt = require('bcryptjs');

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    email: {
      type: DataTypes.STRING,
      primaryKey: true
    },
    phone: {
      type: DataTypes.STRING,
      allowNull: true
    }
  }, {
    instanceMethods:{
      updatePassword: function(newPass, callback){
        console.log("current pass in update: " + this.password);
        bcrypt.genSalt(10, function(err,salt){
          bcrypt.hash(newPass, salt, function(err, hashed){
            console.log("current pass: " + this.password);
            this.password = hashed;
            return callback();
          });
        });
      },
      comparePassword: function(password, callback){
        bcrypt.compare(password, this.password, function(err, isMatch){
          if(err) {
            throw err;
          }
          callback(isMatch);
        });
      }
    }

the first log console.log("current pass in update: " + this.password); prints password of the current object but the second console.log("current pass: " + this.password); does not work and it prints an error: TypeError: Cannot read property 'password' of undefined. Why it happened and how to solve ?



via Thach Huynh

No comments:

Post a Comment