首页 > 解决方案 > 在 nodejs 中,如何使用 sequelize.bulkcreate 将数据插入 MySQL?

问题描述

我已经用谷歌搜索并查找了使用 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

模型/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)
})

模型/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文件中编写代码,但失败了。

请帮忙在哪里写代码

标签: mysqlnode.jssequelize.jsbulkinsert

解决方案


推荐阅读