DEV Community

Cover image for Set up MySQL with Sequelize in NodeJS :
Rahul Kumar
Rahul Kumar

Posted on

Set up MySQL with Sequelize in NodeJS :

  • First of all we have to create a User of the MySQL database .
create database devdb;

create user dev identified by 'devpass';

use devdb;

grant all privileges on devdb.* to dev;
Enter fullscreen mode Exit fullscreen mode
  • Then we have to install sequelize as an orm(object relational mapper ) and mysql2 as the database into our project .
$ npm i mysql2 sequelize 

$ touch db.js
Enter fullscreen mode Exit fullscreen mode
  • connecting to a database :
const sequilize = require('sequilize')

const db = new Sequilize(database, user, password{

  host : 'localhost',
  dilect : mysql,
  pool: {
  min : 0,
  max : 5,
  }
});
Enter fullscreen mode Exit fullscreen mode
  • Create our Model :
const Post = db.define('Post', {
  id: {
  type: Sequilize.INTEGER,
  autoIncrement: true,
  primaryKey: true
  },
  name:{
  type: Sequilize.STRING,
  allowNull: false
  },
});

db.sync()
  .then(() => {
  console.log('Database has been created');
})
.catch((err) => {
  console.log('error creating database '+ err);
})

exports = module.exports = {
 User 
}

node db.js
Enter fullscreen mode Exit fullscreen mode

Thank You For Reading

Top comments (0)