我正在使用Sequelize v4.2和Express v4.15.2并尝试设置模型并将它们相互关联。即使在查看Express/Sequelize tutorial以及v4 migration docs之后,我也很难找到任何有效的v4.x Sequelize示例。
目前,我在尝试设置初始模型和关联时收到以下错误。
/Users/james/Sites/awesome-app/server/node_modules/sequelize/lib/associations/mixin.js:80
if (!target.prototype || !(target.prototype instanceof this.sequelize.Model)) {
TypeError: Cannot read property 'prototype' of undefined
at Function.<anonymous> (/Users/james/Sites/awesome-app/server/node_modules/sequelize/lib/associations/mixin.js:80:16)
我的模型设置文件(index.js
)看起来像......
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
let db = {};
let sequelize = undefined;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf(".") !== 0) && (file !== 'index.js');
})
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
我失败的第一个模型(address.js
)看起来像......
module.exports = function(sequelize, DataTypes) {
var Address = sequelize.define('Address', {
street: DataTypes.STRING,
city: DataTypes.STRING,
state: DataTypes.STRING,
zip: DataTypes.STRING,
});
Address.associate = function(models) {
Address.belongsTo(models.attendeeGroup, {
onDelete: 'CASCADE',
foreignKey: {
allowNull: false
},
});
}
return Address;
};
我希望设置我的数据库表并将各种模型相互关联。我还缺少另一种设置吗?
答案 0 :(得分:1)
我想要关联的模型被错误命名/大写。我有Address.belongsTo(models.attendeeGroup, {
其中attendeeGroup
是骆驼案例,但事实上它需要像AttendeeGroup
那样大写,这是我其他模型的名称。
我更改了此模型名称后,我的数据库已成功创建。