Sequelize TypeError Associate不是Function

时间:2016-03-25 01:04:36

标签: node.js express sequelize.js

当我将关联模型传递给我的db对象时,我正在创建一对多关系并遇到一个奇怪的错误。我不明白错误将来自何处,因为该方法遵循文档。我是否需要在目标模型中编写参考文献?

错误:

db.DiscoverySource.associate(db);
                   ^

TypeError: db.DiscoverySource.associate is not a function
    at Object.<anonymous> (/Users/user/Desktop/Projects/node/app/app/models/db-index.js:33:20)

来源模型(一个)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
},{
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' }),
            Organization.hasMany(db.DiscoverySource, { foreignKey: 'organization_id' });
        },
    }
});
    return Organization;
}

目标(很多)discovery-source.js:

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,
});
    return DiscoverySource;
}

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.Member = sequelize.import(__dirname + "/member");

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

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

db.DiscoverySource = sequelize.import(__dirname + "/discovery-source");

db.User.associate(db);
db.Organization.associate(db);
db.DiscoverySource.associate(db);

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

sequelize.sync();

module.exports = db;

1 个答案:

答案 0 :(得分:2)

由于您未在associate中为DiscoverySource定义classMethods,因此您收到了错误消息。看起来你不需要打电话,所以只需完全删除该行。