Search code examples
javascriptnode.jssequelize.jsbcrypt

Why is my var being returned as undefined when adding .methods to it?


I'm attempting to add bycrypt to an authentication table but I'm getting an error that authTable is undefined when attempting to add the generateHash and validPassword methods. Is there something i'm not understanding about the authTables.methods portion?

The code works when I comment out the generateHash and validPassword portion which leads me to believe that .methods is the hang up.

var bcrypt = require("bcryptjs");

module.exports = function (sequelize, DataTypes) {
  var authTable = sequelize.define("authTable", {

    username: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      len: [1, 30]
    }
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      len: [6, 20]
    }
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      isEmail: true,
      len: [1]
    }
  }
});

authTable.methods.generateHash = function(password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null);
};

authTable.methods.validPassword = function(password) {
  return bcrypt.compareSync(password, this.local.password);
};

return authTable;
}

I would expect this to go to the table within the database with an encrypted password.

The errors i'm receiving are:

TypeError: Cannot set property 'generateHash' of undefined.

TypeError: Cannot set property 'validPassword' of undefined


Solution

  • I'm getting an error that authTable is undefined

    No, you don't. You get an error that authTable.methods is undefined.

    define returns an instance of Model, and as you can see in the documentation of Model, it does not have a property named methods, ergo, authTable.methods will evaluate to undefined.