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