How to create mysql database with sequelize (nodejs)

I try to automate the process of creating db and tables as much as possible. Is it possible to create a database through sequelize? Can I create a connection string that only connects to the server and not directly to db?

+4
source share
2 answers

Short answer: Of course you can!

Here is how I did it:

//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.
});

PS Where to place the code will depend on your needs. Inside the initial migration file worked for me.

+2
source

Here are the basic steps to populate mySql tables with the secelize and sequelize-fixtures modules:

step 1: model creation

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: . 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!!!");
});
+1

Source: https://habr.com/ru/post/1664402/


All Articles