Building a CRUD API with Node.js, Express and MYSQL/MSSQL/Postgres using Sequelize ORM

Create a project with the following command

npm init -y

Now navigate to your project folder run following command to install all dependencies

npm i -S dotenv express joi joi-objectid lodash sequelize

Now install dependency for dialect according to your DBMS, I am going to use MYSQL so, I will install dependency for MYSQL dialect

# One of the following:
npm i pg pg-hstore # Postgres
npm i mysql2 # MYSQL
npm i mariadb # MariaDB
npm i sqlite3 # SQLite
npm i tedious # Microsoft SQL Server

Environment Variables

create a .env file in the root folder of your project and paste the following code in it

DB_HOST=localhost
DB_NAME=node_mysql
DB_USERNAME=root
DB_PASSWORD=

change values of these variables according to your database connection information. now to configure these environment variables

Movie Model

In your project create Movie.js file in src/Models folder and paste the following content

module.exports = (sequelize, Sequelize) => {
    const Movie = sequelize.define('movies', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
        },
        name: {
            type: Sequelize.STRING,
            allowNull: false
        },
        createdAt: {
            type: Sequelize.DATE,
            allowNull: false,
            defaultValue: Sequelize.NOW
        },
        updatedAt: {
            type: Sequelize.DATE,
            allowNull: false,
            defaultValue: Sequelize.NOW
        }
    });

    return Movie;
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *