user3386826
user3386826

Reputation: 437

Sequelize v4 | Instance Methods not working

I've been trying to update my code to accommodate the newest upgrades to Sequelize. I'm using

The Problem

I can't seem to set the User model properly. I've implemented some instance methods that don't seem to be working. The class must not be instantiated properly.

user.js

module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('user', {
    attributes ....
  }, { 
    hooks: { 
      afterCreate(user, options) {
        user.testFunction();
      }
    }
  });

  // Instance methods
  User.prototype.testFunction = () => {
    this.firstName = "John";
  }

  // Class methods
  User.anotherTestFunction = () => {
    User.findOne().then(() => doSomething());
  }

  return User;
}

index.js

var sequelize;
sequelize = new Sequelize(config.DATABASE_URL);

db.User = sequelize.import(__dirname + '/user.js');

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

usersController.js

var db = require('../path/to/db');

function create_post_function = (req, res) => {
  var body = getBody();
  db.User.create(body).then(user => respondSuccess());
}

Now, everything in this example works perfectly EXCEPT the instance method!!!

I'm continually getting TypeError: Cannot set property 'firstName' of undefined

For some reason, it's not applying the instance method to the sequelize Model. Very strange, but I'm probably doing something noticeably wrong and not seeing it.

Really appreciate any help!

Upvotes: 10

Views: 7670

Answers (1)

doublesharp
doublesharp

Reputation: 27609

You can't use arrow functions since they can't access this in the appropriate context (it will reference the parent scope). Try writing them like this -

// Instance methods
User.prototype.testFunction = function testFunction() {
  this.firstName = "John";
}

// Class methods
User.anotherTestFunction = function anotherTestFunction() {
  User.findOne().then(() => doSomething());
}

Upvotes: 38

Related Questions