Published:

Sequelize + MySQL - Create database if it doesn't exist

Tutorial built with Node.js, Sequelize and MySQL

This is a quick post to show how to automatically create a MySQL database on app startup with Sequelize if the database doesn't already exist.

The below code snippet is the Sequelize + MySQL Database Wrapper from a Node.js API I posted recently, for details about the api or to run the code on your local machine see Node.js + MySQL - Simple API for Authentication, Registration and User Management.

 

Sequelize + MySQL Database Wrapper

Path: /_helpers/db.js

The database wrapper connects to MySQL using Sequelize and the MySQL2 client, and exports an object containing all of the database model objects in the application (currently only User). It provides an easy way to access any part of the database from a single point.

The initialize() function is executed once on api startup and performs the following actions:

  • Connects to MySQL server using the mysql2 db client and executes a query to create the database if it doesn't already exist.
  • Connects to the database with the Sequelize ORM.
  • Initializes the User model and attaches it to the exported db object.
  • Automatically creates tables in MySQL database if they don't exist by calling await sequelize.sync(). For more info on Sequelize model synchronization options see https://sequelize.org/master/manual/model-basics.html#model-synchronization.
const config = require('config.json');
const mysql = require('mysql2/promise');
const { Sequelize } = require('sequelize');

module.exports = db = {};

initialize();

async function initialize() {
    // create db if it doesn't already exist
    const { host, port, user, password, database } = config.database;
    const connection = await mysql.createConnection({ host, port, user, password });
    await connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);

    // connect to db
    const sequelize = new Sequelize(database, user, password, { dialect: 'mysql' });

    // init models and add them to the exported db object
    db.User = require('../users/user.model')(sequelize);

    // sync all models with database
    await sequelize.sync();
}

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.