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:
ER_BAD_DB_ERROR: Unknown database 'mytest'
I'd like to handle that error, use the creds I provided (or a different set of creates with create permissions), and run CREATE DATABASE mytest.
Sequelize + MySQL Database Wrapper Connects to MySQL server using the mysql2 db client and executes a query to create the database if it doesn't already exist.
There are two ways you can create a table using Sequelize: Using the Model. sync() method. Using sequelize-cli database migration system.
Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.
I may have a reasonable solution. I am sure it could be written more cleanly though.
For this example I'm using Postgres, the answer would be slightly different for MySQL. I'm heavily borrowing from this answer: node-postgres create database
In database.js I have the following init function
var Sequelize = require('sequelize'), pg = require('pg'); module.exports.init = function(callback) { var dbName = 'db_name', username = 'postgres', password = 'password', host = 'localhost' var conStringPri = 'postgres://' + username + ':' + password + '@' + host + '/postgres'; var conStringPost = 'postgres://' + username + ':' + password + '@' + host + '/' + dbName; // connect to postgres db pg.connect(conStringPri, function(err, client, done) { // create the db and ignore any errors, for example if it already exists. client.query('CREATE DATABASE ' + dbName, function(err) { //db should exist now, initialize Sequelize var sequelize = new Sequelize(conStringPost); callback(sequelize); client.end(); // close the connection }); }); };
The init
function is creating the database before sequelize
is called. It first opens a connection to postgres and creates the database. If the database already exists, an error will be thrown which we are ignoring. Once it is created we initialize sequelize
and send it to the callback. Importantly, if the database already exists it will not be overwritten.
In app.js I receive the database instance and send it over to whichever module needs it, in this case it is passport.
require('./server/config/database.js').init(function(database) { require('./server/config/passport.js')(passport, database); });
In my case I was using sqlite, but the idea was the same. I needed to create the database first with sqlite3
.
const sqlite = require('sqlite3'); const db = new sqlite.Database('/path/to/database.sqlite'); const sequelize = new Sequelize('database', '', '', { dialect: 'sqlite', storage: '/path/to/database.sqlite', ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With