续集表非关联问题

时间:2015-12-26 20:35:54

标签: node.js express sequelize.js

我遇到了一个问题,我试图在一个路由POST方法中填充多个表的值。我阅读了文档中有关关联创建的部分并模仿了示例,但是我遇到了一个问题:

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

我不确定为什么会发生这种情况,因为我正在使用应该创建关联的.belongsTo方法。

这是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
    },
    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;
}

这是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
});

    return Organization;
}

这是模型索引文件,其中表附加到db对象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;

以下是路线(/sign-up是我参考的地方):

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;

1 个答案:

答案 0 :(得分:0)

您只关联模型注释

db.Annotation.associate(db);

忘记

db.User.associate(db);