gpt4 book ai didi

javascript - Sequelize & Express 模型和关联设置

转载 作者:行者123 更新时间:2023-11-30 21:18:51 26 4
gpt4 key购买 nike

背景

我正在使用 Sequelize v4.2 和 Express v4.15.2 并尝试设置模型并将它们相互关联。即使在查看此 Express/Sequelize tutorial 之后,我也很难找到任何有效的 v4.x Sequelize 示例以及 v4 migration docs .

问题

目前,我在尝试设置初始模型和关联时收到以下错误。

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

我希望设置我的数据库表并将各种模型相互关联。我还缺少其他设置吗?

最佳答案

我想要关联的模型的名称/大写不正确。我有 Address.belongsTo(models.attendeeGroup, { 其中 attendeeGroup 是驼峰式的,但实际上它需要像 AttendeeGroup 这样大写我的另一个模型的名称。

更改此模型名称后,我的数据库已成功创建。

关于javascript - Sequelize & Express 模型和关联设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45390389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com