node.jsnpmsequelize.jsmysql-connectormysql2

Can I use "mysql" instead of "mysql2" with sequelize in Node.js?


So, I have been using mysql npm package in my projects for sometime now and I want to use Sequelize for some part of my one project. But it was throwing an error when I am passing "mysql" as in value in dialect.

Here is the error:

throw new Error(Please install ${moduleName} package manually);

Error: Please install mysql2 package manually

Here is my sequelize code:

const sequelize =  new Sequelize({
    dialect: "mysql",
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_DATABASE,
    port: process.env.DB_PORT
});

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

sequelize.close();

So my first question is can I use mysql, or should I switch to mysql2? Or if I were to switch to the mysql2, will replacing mysql in dependencies with mysql2 work (without changing anything i.e. queries or methods from mysql)?

Here what I mean:

const mysql = require("mysql");

const mysql = require("mysql2");


Solution

  • Sequelize specifically requires the mysql2 package as its default MySQL dialect engine. Thus, for using Sequelize, you cannot use the mysql package; you must use mysql2.

    If you switch from mysql to mysql2, it should generally work seamlessly for most use cases because mysql2 aims to be a drop-in replacement for mysql.

    So, uninstall mysql using the command npm uninstall mysql and then install mysql2 using the command npm i mysql2

    I hope this solves your problem 🤞