Open In App

Node.js MySQL-Create Table Using Sequelize

Introduction to Sequelize: Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. Its features are solid transaction support, relations, eager and lazy loading, read replication and many more.

Connect to MySql Database using Sequelize: 



Configure database.js: SequelizeDemo>utils>database.js 

Note: Make sure the database that you are using is created in your database.



Configure user.js:  




// Include Sequelize module.
const Sequelize = require('sequelize')
  
// Import sequelize object, 
// Database connection pool managed by Sequelize.
const sequelize = require('../utils/database')
  
// Define method takes two arguments
// 1st - name of table
// 2nd - columns inside the table
const User = sequelize.define('user', {
  
    // Column-1, user_id is an object with 
    // properties like type, keys, 
    // validation of column.
    user_id:{
  
        // Sequelize module has INTEGER Data_Type.
        type:Sequelize.INTEGER,
  
        // To increment user_id automatically.
        autoIncrement:true,
  
        // user_id can not be null.
        allowNull:false,
  
        // For uniquely identify user.
        primaryKey:true
    },
  
    // Column-2, name
    name: { type: Sequelize.STRING, allowNull:false },
  
    // Column-3, email
    email: { type: Sequelize.STRING, allowNull:false },
  
    // Column-4, default values for
    // dates => current time
    myDate: { type: Sequelize.DATE, 
            defaultValue: Sequelize.NOW },
  
     // Timestamps
     createdAt: Sequelize.DATE,
     updatedAt: Sequelize.DATE,
})
  
// Exporting User, using this constant
// we can perform CRUD operations on
// 'user' table.
module.exports = User

Configure app.js:  




// Import the sequelize object on which 
// we have defined model. 
const sequelize = require('./utils/database'
    
// Import the user model we have defined 
const User = require('./models/user) 
    
// Create all the table defined using  
// sequelize in Database 
    
// Sync all models that are not 
// already in the database 
sequelize.sync()  
    
// Force sync all models 
// It will drop the table first  
// and re-create it afterwards 
sequelize.sync({force:true})

Steps to run the program:  

npm install mysql2
npm install sequelize
node app.js

use database geeksforgeeks
desc users;

 


Article Tags :