Sequelize TypeError Associate 不是函数

Sequelize TypeError Associate is not a Function

我正在创建一对多关系,当我将关联模型传递给我的 db 对象时,运行 出现了 st运行ge 错误。我不明白错误将来自哪里,因为该方法遵循文档。我需要在目标模型中编写参考吗?

错误:

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;
}

目标(许多)发现-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;

您收到错误消息是因为您没有在 classMethods 中为 DiscoverySource 定义 associate。看起来您不需要调用它,所以只需完全删除该行即可。