cphill
cphill

Reputation: 5914

Sequelize Association Error Not Associated

I am trying to associate my User model with my Organization model, but I'm running into an error that says, Error: user is not associated to organization! despite the fact that I am following the process to associate the User to my Organization. Is it possible that the type of association method that I am using is causing the problem?

User Model (user.js):

var bcrypt   = require('bcrypt-nodejs');

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
    user_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.STRING,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.STRING,
        field: 'last_name'
    },
    email: {
        type: DataTypes.STRING,
        isEmail: true,
        unique: true
    },
    password: DataTypes.STRING,
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    }
}, {
    freezeTableName: true,
    classMethods: {
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
        associate: function(db) {
            User.belongsTo(db.Organization, {foreignKey: 'organizationId'});
        },
    },
    instanceMethods: {
        validPassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
    },


});
    return User;
}

Organization model (organization.js):

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,
    members: DataTypes.STRING
},{
    freezeTableName: true
});

    return Organization;
}

index for tables to connect (db-index.js):

var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host:'localhost',
    port:'3306',
    dialect: 'mysql'
});

sequelize.authenticate().then(function(err) {
    if (!!err) {
        console.log('Unable to connect to the database:', err)
    } else {
        console.log('Connection has been established successfully.')
    }
});

var db = {}

db.Organization = sequelize.import(__dirname + "/organization");

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

db.Records = sequelize.import(__dirname + "/records");

db.User.associate(db);
db.Records.associate(db);

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

sequelize.sync();

module.exports = db;

Are of a route call that triggers this error:

appRoutes.route('/sign-up/organization')

    .get(function(req, res){
        models.User.find({
            where: {
                user_id: req.user.email
            }, attributes: [ 'user_id', 'email'
            ]
        }).then(function(user){
            res.render('pages/sign-up-organization.hbs',{
                user: req.user
            });
        })

    })

    .post(function(req, res, user){
        models.Organization.create({
            organizationName: req.body.organizationName,
            admin: req.body.admin,
            user: {
                organizationId: req.body.organizationId
            }
        }, { include: [models.User] }).then(function(){
            console.log(user.user_id);
            res.redirect('/app');
        }).catch(function(error){
            res.send(error);
            console.log('Error at Post');
        })
    });

Upvotes: 2

Views: 1821

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28778

You need to set up the reverse of the association, Organization hasMany Users

Upvotes: 3

Related Questions