Search code examples
mysqldatabasesequelize.jsdatabase-create

How to create mysql database with sequelize (nodejs)


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?


Solution

  • 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.