如何使用 sequelize (nodejs) 创建 mysql 数据库

How to create mysql database with sequelize (nodejs)

我正在尝试尽可能自动化创建数据库和表的过程。是否可以通过 sequelize 创建数据库?我可以创建一个仅连接到服务器而不是直接连接到数据库的连接字符串吗?

以下是使用 sequelize 和 sequelize-fixtures 模块填充 mySql 表的主要步骤:

第 1 步:创建模型

module.exports = function(sequelize, Sequelize) {
// Sequelize user model is initialized earlier as User
const User = sequelize.define('user', {
    id          :       { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
    firstname   :       { type: Sequelize.STRING },
    lastname    :       { type: Sequelize.STRING },
    email       :       { type: Sequelize.STRING, validate: {isEmail:true} },
    password    :       { type: Sequelize.STRING }, 
});

// User.drop();
return User;
}

第 2 步:创建一个配置文件来存储数据库配置

{
  "development": {

    "username": "root",
    "password": null,
    "database": "hotsausemedia",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "test": { 
    "username": "",
    "password": null,
    "database": "hotsausemedia",
    "host": "",
    "dialect": "mysql"
  },
  "production": {
    "username": "",
    "password": null,
    "database": "hotsausemedia",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}

第 3 步:创建 sequelize-fixture 来填充表。这是一个 json 文件的示例,用于填充数据

[
    {
        "model": "product",
        "keys": ["id"],
        "data": {
            "id": 1,
            "name": "Product #1",
            "src": "./assets/img/products/01.jpg",
            "price": 9.99,
            "desc": "Product description..."
        }
    },
    {
        "model": "product",
        "keys": ["id"],
        "data": {
            "id": 2,
            "name": "Product #2",
            "src": "./assets/img/products/02.jpg",
            "price": 19.99,
            "desc": "Product description..."
        }
    },
    ...

]

第 4 步:连接到数据库并填充表

models.sequelize.sync().then(() => {
    console.log('You are connected to the database successfully.');
    sequelize_fixtures.loadFile('./fixtures/*.json', models).then(() =>{
        console.log("database is updated!");
   });
   }).catch((err) => {
       console.log(err,"Some problems with database connection!!!");
});

简短回答:当然可以!

我是这样完成的:

//create the sequelize instance, omitting the database-name arg
const sequelize = new Sequelize("", "<db_user>", "<db_password>", {
  dialect: "<dialect>"
});

return sequelize.query("CREATE DATABASE `<database_name>`;").then(data 
=> {
  // code to run after successful creation.
});

P.S。放置代码的位置取决于您的需要。在初始迁移文件中为我工作。

尽管这个问题已在不久前得到回答,但请看一下另一个非常相似的问题(可能是重复的?)的答案(我的),该问题绝对适用于此:

想法是使用 Sequelize 迁移,让 Sequelize 使用以下格式的文件处理迁移:

module.exports = {
  up: (queryInterface, Sequelize) => {
    // logic for transforming into the new state
  },
  down: (queryInterface, Sequelize) => {
    // logic for reverting the changes
  }

是的,它也处理回滚。使这个过程很容易实现自动化。