cphill cphill - 1 month ago 17
Node.js Question

Sequelize Tables not Associated Issue

I am running into an issue where I am trying to populate a value for multiple tables in one route POST method. I read the section in the documentation for creation with associations and mimicked the example, but I get an issue:

Error: organization is not associated to user!
at validateIncludedElement (/Users/user/Desktop/Projects/node/app/node_modules/sequelize/lib/model.js:560:11)


I am not sure why this is happening since I am using the
.belongsTo
method that should create the association.

Here is the User.js model:

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

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
user_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
organizationName: {
type: DataTypes.STRING,
field: 'organization_name',
unique: 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,

}, {
freezeTableName: true
},{
classMethods: {
associate: function(db) {
User.belongsTo(db.Organization)
}
}
});
return User;
}


Here is the organization.js 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,
members: DataTypes.STRING
});

return Organization;
}


Here is the model index file where the tables are attached to a db object 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.Annotation = sequelize.import(__dirname + "/annotation");


db.Annotation.associate(db);

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

sequelize.sync();

module.exports = db;


Here are the routes (
/sign-up
is where I am making the reference):

var express = require('express');
var siteRoutes = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var models = require('../models/db-index');

/*==== Passport Configuration ====*/

// Serialize sessions
passport.serializeUser(function(user, done) {
console.log(user.user_id + "Serializing");
done(null, user.user_id);
});

passport.deserializeUser(function(user_id, done) {
models.User.find({where: {user_id: user_id}}).then(function(user){
done(null, user);
}).error(function(err){
done(err, null);
});
});


passport.use('local', new LocalStrategy({
passReqToCallback : true,
usernameField: 'email'
},
function(req, email, password, done) {
//Find user by email
models.User.findOne({
where: {
email: req.body.email,
password: req.body.password
}
}).then(function(user) {
return done(null, user);
})
.catch(function(err) {
return done(null, false, req.flash('message', 'Email not found.'));
});
}
));




/*==== Index ====*/

siteRoutes.get('/', function(req, res){
res.render('pages/index.hbs');
});

/*==== Login ====*/


siteRoutes.route('/login')

.get(function(req, res){
res.render('pages/login.hbs');
})

.post(passport.authenticate('local', {
successRedirect: '/app',
failureRedirect: '/login',
failureFlash: 'Invalid username or password.'
}));



siteRoutes.route('/sign-up')

.get(function(req, res){
res.render('pages/sign-up.hbs');
})

.post(function(req, res){

models.User.create({
Organization: {
organizationName: req.body.organizationName
},
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
},{include: [models.Organization]}).then(function() {
res.redirect('/');
}).catch(function(error){
res.send(error);
})

});







module.exports = siteRoutes;

Answer

you only associate model annotation

db.Annotation.associate(db);

forget

db.User.associate(db);