0

I am defining a getter method on my Users model like so,

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Users = sequelize.define('Users', {
    name: DataTypes.STRING,
    uuid: {
      type: DataTypes.INTEGER, 
      allowNull: false, 
      primaryKey: true
    }, 
    poll_ids: DataTypes.ARRAY(DataTypes.INTEGER)
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        Users.hasMany(models.Polls, {
          foreignKey: 'userId'
        });
      }
    }, 
    getterMethods: {
      getUUID() {
        return this.getDataValue('uuid');
      }
    }
  });
  return Users;
};

And I am trying to run it like so,

models.Users.create({
        name: name, 
        uuid: uuid, 
        poll_ids: poll_ids
    }).then((user) => {
        console.log(user.getUUID());
    });

However, I get the following error when I do that.

Unhandled rejection TypeError: user.getUUID is not a function

Note: I have defined my models and migrations with sequelize-cli. I added the getterMethods to the model file after doing the migration. I ran an undo migrate, sync of the database and migrate again to make sure the migration files reflected the change to my model. However, I am not sure that is the way to go about doing an update on the migration file. Where am I going wrong?

random_coder_101
  • 1,782
  • 3
  • 24
  • 50

2 Answers2

0

Okay, finally got something to work. Defining it as part of the model doesn't work, but for some reason defining it as part of the property works.

module.exports = function(sequelize, DataTypes) {
  var Users = sequelize.define('Users', {
    name: DataTypes.STRING,
    uuid: {
      type: DataTypes.INTEGER, 
      allowNull: false, 
      primaryKey: true, 
      get() {
        return this.getDataValue('uuid');
      }
    }, 
    poll_ids: DataTypes.ARRAY(DataTypes.INTEGER)
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        Users.hasMany(models.Polls, {
          foreignKey: 'userId'
        });
      }
    }
  });
  return Users;
};

In the routes file

models.Users.create({
        name: name, 
        uuid: uuid, 
        poll_ids: poll_ids
    }).then((user) => {
        console.log('Finally');
        console.log(user.get('uuid'));
    });
random_coder_101
  • 1,782
  • 3
  • 24
  • 50
0

I haven't seen it in the docs for some time, but defining instanceMethods seems to work for what you're looking to achieve with getUUID()

Replace getterMethods: with instanceMethods and you should be able to access .getUUID( on instances of the Users model.