#mysql #node.js #sequelize.js #bulkinsert
#mysql #node.js #sequelize.js #bulkinsert
Вопрос:
Я погуглил и посмотрел коды, создающие данные с помощью sequelize.
Однако авторы слишком хороши, чтобы игнорировать эту жалкую, но основную проблему.
Где мне написать код?
Вот мой каталог.
Modeling
/config
config.json
/migrations
(empty)
/models
index.js
platoon.js
section.js
squad.js
team.js
/node_moduels
/seeders
(empty)
app.js
package-lock.json
package.json
Код, который я пытаюсь добавить в свой код, это
Team.bulkCreate([
{ name: 'team1', platoonID: "4" },
{ username: 'team2', platoonID: "4" },
{ username: 'team3', platoonID: "4" },
{ username: 'team4', platoonID: "4" },
{ username: 'team5', platoonID: "4" }
]).then(() => { // Notice: There are no arguments here, as of right now you'll have to...
return Team.findAll();
}).then(teams => {
console.log(teams) // ... in order to get the array of user objects
})
Но код возвращает
Executing (default): INSERT INTO `teams` (`id`,`name`,`created_at`,`platoonID`) VALUES (NULL,'1팀',now(),'4'),(NULL,NULL,now(),'4'),(NULL,NULL,now(),'4'),(NULL,NULL,now(),'4'),(NULL,NULL,now(),'4');
Executing (default): CREATE TABLE IF NOT EXISTS `platoons` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(20) NOT NULL UNIQUE, `created_at` DATETIME NOT NULL DEFAULT now(), PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
(node:15874) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Table 'nodejs.teams' doesn't exist
at Query.formatError (/Users/mac/Desktop/modeling/node_modules/sequelize/lib/dialects/mysql/query.js:239:16)
at Query.run (/Users/mac/Desktop/modeling/node_modules/sequelize/lib/dialects/mysql/query.js:54:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:15874) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15874) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Executing (default): SHOW INDEX FROM `platoons` FROM `nodejs`
Executing (default): CREATE TABLE IF NOT EXISTS `sections` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(20) NOT NULL UNIQUE, `created_at` DATETIME NOT NULL DEFAULT now(), `platoonID` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`platoonID`) REFERENCES `platoons` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
Executing (default): SHOW INDEX FROM `sections` FROM `nodejs`
Executing (default): CREATE TABLE IF NOT EXISTS `squads` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(20) NOT NULL UNIQUE, `created_at` DATETIME NOT NULL DEFAULT now(), `platoonID` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`platoonID`) REFERENCES `platoons` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
Executing (default): SHOW INDEX FROM `squads` FROM `nodejs`
Executing (default): CREATE TABLE IF NOT EXISTS `teams` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(20) NOT NULL UNIQUE, `created_at` DATETIME NOT NULL DEFAULT now(), `sectionID` INTEGER, `squadID` INTEGER, `platoonID` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`sectionID`) REFERENCES `sections` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (`squadID`) REFERENCES `squads` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (`platoonID`) REFERENCES `platoons` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
Executing (default): SHOW INDEX FROM `teams` FROM `nodejs`
connection succeed
Я написал этот код models/index.js
в.
Я предполагаю, что код должен быть записан models/index.js
, но, похоже, нет.
Как я могу вставить объемные данные в MySQL с помощью sequelize.bulkcreate
?
models/index.js
const Sequelize = require('sequelize');
const Team = require("./team");
const Section = require("./section");
const Squad = require("./squad");
const Platoon = require("./platoon");
const env = process.env.NODE_ENV || 'development';
const config = require('../config/config')[env];
const db = {};
const sequelize = new Sequelize(config.database, config.username, config.password, config);
db.sequelize = sequelize;
db.Team = Team;
db.Section = Section;
db.Squad = Squad;
db.Platoon = Platoon;
Team.init(sequelize);
Section.init(sequelize);
Squad.init(sequelize);
Platoon.init(sequelize);
Team.associate(db);
Section.associate(db);
Squad.associate(db);
Platoon.associate(db);
//Team.bulkCreate([
// { name: 'team1', platoonID: "4" },
// { username: 'team2', platoonID: "4" },
// { username: 'team3', platoonID: "4" },
// { username: 'team4', platoonID: "4" },
// { username: 'team5', platoonID: "4" }
//]).then(() => {
// return Team.findAll();
//}).then(teams => {
// console.log(teams)
//})
module.exports = db;
Team.bulkCreate([
{ name: 'team1', platoonID: "4" },
{ username: 'team2', platoonID: "4" },
{ username: 'team3', platoonID: "4" },
{ username: 'team4', platoonID: "4" },
{ username: 'team5', platoonID: "4" }
]).then(() => {
return Team.findAll();
}).then(teams => {
console.log(teams)
})
models/team.js
const Sequelize = require("sequelize");
module.exports = class Team extends Sequelize.Model{
static init(sequelize) {
return super.init({
name : {
type : Sequelize.STRING(20),
allowNull : false,
unique : true,
},
created_at : {
type : Sequelize.DATE,
allowNull : false,
defaultValue : sequelize.literal('now()'),
},
},{
sequelize,
timestamps : false,
underscored : false,
modelName : 'Team',
tableName : 'teams',
paranoid : false,
charset : 'utf8',
collate : 'utf8_general_ci',
});
}
static associate(db) {
db.Team.belongsTo(db.Section, {
foreignKey : "sectionID",
targetKey : 'id'
});
db.Team.belongsTo(db.Squad, {
foreignKey : "squadID",
targetKey : 'id'
});
db.Team.belongsTo(db.Platoon, {
foreignKey : "platoonID",
targetKey : 'id'
});
};
}
Я пытался записать код в models/index.js
файл, но это не удалось.
Пожалуйста, помогите, где написать код
Комментарии:
1. Кажется, вы указали
username
вместоname
почти во всех ваших объектах, которые вы пытаетесь вставить2. @Anatoly Извините, но имена объектов связаны с ошибкой? Потому что, когда я создаю строку с помощью MySQL workbench, ошибка не возникает.
3. В какой схеме вы храните
teams
таблицу?4. @Anatoly У меня есть
nodejs
схема, в ней естьteams
таблица и т. Д.5. Используете ли вы
sync
метод экземпляра Sequelize?