MySQL DB Connection with Sequelize ORM

  • To connect a MySQL database with Sequelize ORM in a Node.js application, follow these detailed steps. This guide assumes you have Node.js and npm installed, and that you have a MySQL database accessible either locally or remotely.
  • Step 1: Install Sequelize and MySQL Driver
  • First, you need to install Sequelize along with the MySQL driver. The MySQL driver (`mysql2`) is required for Sequelize to communicate with MySQL databases.

 
    npm install sequelize mysql2

  • This command installs both Sequelize and the `mysql2` package to your project.
  • Step 2: Setting Up Sequelize
  • Create a new file in your project, for example, `sequelize-setup.js`, and set up Sequelize to connect to your MySQL database. You'll need to provide details like your database name, username, password, and host.
  • Here's an example of how you can set it up:

    const { Sequelize } = require('sequelize');

    // Replace the placeholders with your actual database information
    const sequelize = new Sequelize('your_database_name', 'your_username', 'your_password', {
        host: 'your_host', // often 'localhost' if your database is on your local machine
        dialect: 'mysql', // This specifies that you are connecting to a MySQL database
        logging: false, // This disables the SQL logging in the console
    });

    module.exports = sequelize;

  • In this code, replace `'your_database_name'`, `'your_username'`, and `'your_password'` with your actual MySQL database details. The `host` should be set to the address where your MySQL database is hosted (`localhost` if it's installed on your local machine).
  • Step 3: Testing the Connection
  • It's a good practice to test the database connection to ensure everything is set up correctly. You can add a function to your setup file or create a new one to test the connection:

    const sequelize = require('./sequelize-setup');

    async function testDatabaseConnection() {
        try {
            await sequelize.authenticate();
            console.log('Connection has been established successfully.');
        } catch (error) {
            console.error('Unable to connect to the database:', error);
        }
    }

    testDatabaseConnection();

  • This script tries to authenticate with the database using the connection details provided. If successful, it will log a success message; otherwise, it will log an error.
  • Step 4: Using Sequelize with MySQL
  • Once the connection is established, you can start defining models and interacting with your MySQL database using Sequelize. Here's a basic example of defining a model and inserting a record into the database:

    const { Model, DataTypes } = require('sequelize');
    const sequelize = require('./sequelize-setup');

    class User extends Model { }

    User.init({
        // Define model attributes
        firstName: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        lastName: {
            type: DataTypes.STRING,
            // allowNull defaults to true
        },
    }, {
        // Sequelize model options
        sequelize, // Pass the connection instance
        modelName: 'User', // Define the model name
    });

    // Synchronize the model with the database, creating the table if it doesn't exist
    sequelize.sync().then(() => {
        // Insert a new user into the database
        User.create({
            firstName: 'John',
            lastName: 'Doe',
        }).then(john => {
            console.log(john.toJSON());
        });
    });

  • In this example, a `User` model is defined with `firstName` and `lastName` fields. The `sequelize.sync()` method is called to synchronize the model with the database, which includes creating the table if it doesn't exist. Afterward, a new `User` instance is created and saved to the database.
  • This basic workflow demonstrates how to connect to a MySQL database using Sequelize, define models, and perform operations on the database. From here, you can explore more advanced features and functionalities provided by Sequelize, such as associations, transactions, and complex queries.

No comments:

Post a Comment

Date and Time related aggregation functions ($year, $month, $dayOfMonth, $hour, $minute, $second, $dayOfWeek, $dateToString, $dateSubtract, $dateAdd, $isoWeek, $isoDayOfWeek, $dateTrunc, $dateFromString, $dateToParts, $dateFromParts, $dateDiff, $week)

In this blog post, we will explore Date/Time-related Aggregation Functions in MongoDB. MongoDB provides a robust set of aggregation operator...