Sunday 21 May 2017

Getter method not working on PostgreSQL model

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?



via Zaid Humayun

No comments:

Post a Comment