Sequelize Association Error Cannot read property 'getTableName' of undefined

Viewed 23002

I am running into an issue where I get an error message, Unhandled rejection TypeError: Cannot read property 'getTableName' of undefined when I try to associate a table into my query. I have a one-to-one relationship between the tables and am not sure if this is causing the error or if it is somewhere else where I am associating the two tables.

Here is my query:

appRoutes.route('/settings')

    .get(function(req, res, organization){
        models.DiscoverySource.findAll({
            where: { 
                organizationId: req.user.organizationId
            },
            include: [{
                model: models.Organization, through: { attributes: ['organizationName', 'admin', 'discoverySource']}
            }]
        }).then(function(organization, discoverySource){
            res.render('pages/app/settings.hbs',{
                user: req.user,
                organization: organization,
                discoverySource: discoverySource
            });
        })

    })

Here is the models.DiscoverySource model:

module.exports = function(sequelize, DataTypes) {

var DiscoverySource = sequelize.define('discovery_source', {
    discoverySourceId: {
        type: DataTypes.INTEGER,
        field: 'discovery_source_id',
        autoIncrement: true,
        primaryKey: true
    },
    discoverySource: {
        type: DataTypes.STRING,
        field: 'discovery_source_name'
    },
    organizationId: {
        type: DataTypes.TEXT,
        field: 'organization_id'
    },
},{
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            DiscoverySource.belongsTo(db.Organization, {foreignKey: 'organization_id'});
        },
    },
});
    return DiscoverySource;
}

Here is my models.Organization model:

module.exports = function(sequelize, DataTypes) {

var Organization = sequelize.define('organization', {
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        autoIncrement: true,
        primaryKey: true
    },
    organizationName: {
        type: DataTypes.STRING,
        field: 'organization_name'
    },
    admin: DataTypes.STRING
},{
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
        },
    }
});
    return Organization;
}
3 Answers

In my case removing

through: { attributes: [] }

solved the problem.

I was facing the same issue. My Sequelize version 5.22.3. If you are using the same version then please make the following change to your query:

models.DiscoverySource.findAll({
    attributes: ['discoverySource'],
    where: { 
        organizationId: req.user.organizationId
    },
    include: {
        model: models.Organization,
        //rest of the code, if any
    }
})

include doesn't need to be an array any longer.

Related