I am trying to use Sequelize's instance method to validate a password on login attempt. I have defined the User model as :
var User = sequelize.define('User',{ id:{ type:DataTypes.BIGINT, autoIncrement: true, allowNull: false, primaryKey:true }, username:{ type:DataTypes.STRING, unique:true }, password:{ type: DataTypes.STRING }, ... }, { classMethods:{ associate:function(models){ ... } } }, { instanceMethods:{ validatePassword:function(password){ return bcrypt.compareSync(password, this.password); } } } ); return User; }
In my login route I do the following :
Here is the relevant code
var username = req.body.username || ""; var password = req.body.password || ""; models.User.findOne({ where: {username: username} }). then( function(user) { if(user){ console.log(user.validatePassword(password)); } ....
Each time I try to login I get the following error
[TypeError: user.validatePassword is not a function]
What am I doing wrong?
There are two ways you can define instance methods with Sequelize: Adding the function to the prototype object. Adding the function to the model created using ES6 class.
Sequelize set up Install Sequelize database driver for the database you would like to use by running one of the commands below. Install npm package Sequelize-CLI. Create a project folder. In your project folder path, run the command below to initialize Sequelize in the folder.
The create() method is used to insert a single row into your SQL table. When you need to insert multiple rows at once, you need to use the bulkCreate() method instead. Finally, you can also write and execute a raw SQL statement using the sequelize. raw() method.
The Model. upsert() method is a new method added in Sequelize v6 that allows you to perform an update statement only when a row with matching values already exist. To update a row, you need to specify the primary key of the row, which is the id column in case of the Users table.
I think you are using the sequelize model definition api incorrectly. http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models
This is the correct way:
var User = sequelize.define('User',{}, { classMethods: { method1: ... }, instanceMethods: { method2: ... } });
not like this:
var User = sequelize.define('User',{}, { classMethods: { method1: ... } },{ instanceMethods: { method2: ... } });
For anyone who's having a similar problem, I ran into the same issue but using Sequelize 5.21.5. According to this article, Sequelize Instance Methods, starting with Sequelize 4.0 and above, you have to use the prototype methodology in order to define instance methods like so:
// Adding an instance level methods. User.prototype.validPassword = function(password) { return bcrypt.compareSync(password, this.password); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With