Is there a way to have sequelize create the database I\'m trying to connect to if it doesn\'t exist?
I have a raw MySQL instance and I get this error back:
I didn't have this problem with Postgresql but I did have with mysql.
Solution was creating a pre-migrate
script and trigger it before the sequelize migration, here's part of my package.json
:
"db:pre-migrate": "node scripts/createDB.js",
"db:migrate": "npm run db:pre-migrate && node_modules/.bin/sequelize db:migrate",
and similarly to what was proposed in some answer here, you could create this createDB.js
using modules like node-postgres
or mysql
(or any other that connects to mysql with raw queries):
const mysql = require('mysql2/promise');
const dbName = process.env.DB_SCHEMAS || "YOUR_DB";
mysql.createConnection({
host: process.env.DB_HOST || "127.0.0.1",
port: process.env.DB_PORT || "3306",
user : process.env.DB_USER || "root",
password : process.env.DB_PASSWORD || "root",
}).then( connection => {
connection.query(`CREATE DATABASE IF NOT EXISTS ${dbName};`).then((res) => {
console.info("Database create or successfully checked");
process.exit(0);
})
})