malcoauri
malcoauri

Reputation: 12189

Instance methods don't work on Sequelize 4

There is model code:

'use strict';
const bcrypt = require('bcrypt');

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  }, {
    hooks: {
      beforeCreate: user => {
        const salt = bcrypt.genSaltSync();

        user.password = bcrypt.hashSync(user.password, salt);
      }
    },
  });

  User.prototype.isPasswordValid = password => {
    console.log('current_email');
    console.log(this.email);
    //return bcrypt.compareSync(password, this.password);
  };

  User.associate = models => {
    // associations can be defined here
  };

  return User;
};

When I execute this code:

  const user = await User.findOne({ where: { email } });

  if (!user || !user.isPasswordValid(password)) {
    ctx.body = {
      result: RESULT_CODE.ERROR,
      error: ERROR_CODE.UNAUTHORIZED,
    };

    return;   
  }

I see the following output:

current_email
undefined

I don't understand why I can't get access to fields of user.

Versions:

    "sequelize": "4.3.1",
    "sequelize-cli": "4.0.0"

Upvotes: 0

Views: 24

Answers (1)

Anatoly
Anatoly

Reputation: 22758

Try using an usual function and not an arrow function

User.prototype.isPasswordValid = function(password) {
    console.log('current_email');
    console.log(this.email);
    //return bcrypt.compareSync(password, this.password);
  };

Upvotes: 1

Related Questions