使用sequelize在Node.js中自动创建架构

时间:2019-06-17 05:36:09

标签: mysql node.js sequelize.js

我有一个react + node应用程序。我正在使用sequelize创建表。我想让sequelize在mysql中自动创建 schema(不是表,如果不存在则自动创建表),并用一组特定的数据填充其中一个表。

const Sequelize = require('sequelize');
const sequelize = new Sequelize('myschema','username','pass',{
    dialect:'mysql',
    host:'localhost'
});

module.exports = sequelize;

表是自动创建的,但是我想在运行应用程序后也自动创建模式-“ myschema”(以避免在生产中手动创建模式)。

router.post('/somepath',(req,res,next)=>{
const 
pathname=path.join(__dirname,'../','somefile.xlsx');
  let workbook=xlsx.readFile(pathname);
  var sheet_name_list = workbook.SheetNames;
  var data = xlsx.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);//This is an array of json objects

//updating the database.

});

我想在启动时使用json对象数组中的数据填充配置文件表,如果还没有

2 个答案:

答案 0 :(得分:0)

您可以使用sequelize-auto npm。从数据库生成模式和模型很有帮助。

  • 在使用sequelize-auto之前,您需要全局安装正确的方言绑定。您的情况将是
npm install -g mysql
  • 运行以下命令
sequelize-auto -h <host> -d <database> -u <user> -x [password] -p [port]  --dialect [dialect] -o [/path/to/models] -t [tableName]

如果要为所有表生成文件,则跳过最后一部分,即-t [tableName]标志 有关更多详细信息,请参阅NPM的文档。

答案 1 :(得分:0)

这是用于在服务器启动时在表中创建多行

sequelize_object.sync() // is invoked at server startup
.then(res=>{
        const pathname=path.join(__dirname,'somepath','somefile.xlsx');
        let workbook=xlsx.readFile(pathname);
        var sheet_name_list = workbook.SheetNames;

        var data = xlsx.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);//array of json objects

        usertable.bulkCreate(data) //using sequelize to create multiple rows
        .then(response=>{console.log("Records Imported")})
        .catch(err=>{console.log(err)})
        console.log(res.data);
})
.catch(err=>{
        console.log(err);
})