How to create mysql database with sequelize (nodej

2019-06-22 06:56发布

问题:

I am trying to automate the process of creating db and tables as much as possible. Is it possible to create database via sequelize? Can I make a connection string that connects just to server, not to db directly?

回答1:

Short Answer: Sure you can!

Here's how I got it done:

//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. Where to place code would depend on your need. Inside an initial migration file worked for me.



回答2:

Here are main steps to populate mySql tables with sequelize and sequelize-fixtures modules:

step 1: creating model

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

Step 2: creating a config file to store database configs

{
  "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"
  }
}

step 3: creating sequelize-fixture to populate tables. here is an example of a json file to use for populating data

[
    {
        "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..."
        }
    },
    ...

]

step 4: connecting to database and populating tables

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!!!");
});