Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 447
ilija veselica Avatar asked Dec 21 '16 08:12

ilija veselica


People also ask

Can we use Sequelize with MySQL?

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.

How do I create a database using Sequelize?

const { Sequelize } = require("sequelize"); const sequelize = new Sequelize("BlogDB", "root", "root", { host: "localhost", dialect: "mysql", }); After that, you can create the Sequelize models to represent the tables in your database. You can also let Sequelize create the tables in your database using the Model.

How do I use Sequelize with node js?

Sequelize set up Install Sequelize database driver for the database you would like to use by running one of the commands below. Install npm package Sequelize-CLI. Create a project folder. In your project folder path, run the command below to initialize Sequelize in the folder.

What is difference between Sequelize and MySQL?

MySQL can be classified as a tool in the "Databases" category, while Sequelize is grouped under "Object Relational Mapper (ORM)". "Sql" is the top reason why over 778 developers like MySQL, while over 17 developers mention "Good ORM for node. js" as the leading cause for choosing Sequelize.


1 Answers

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.

like image 161
osifo Avatar answered Sep 23 '22 20:09

osifo