MANY-TO-MANY Association in MYSQL Database using Sequelize async/await with Node.js

The many-to-many association is the trickiest relationship to represent and implement in a relational database. This tutorial provides a profound explanation of the many-to-many association and how to define and implement it using Sequelize async/await to interact with MySQL database in a Node.js API.

Related Articles:

What is the Many-To-Many association in Relational Database?

The many-To-Many association is a relationship where more than one record in table A is related to more than one record in another table B. An example of a many-to-many relationship is the one between employees and projects. An employee can work on many projects, and a project can include and be done by many employees.

In a relational database, there are three ways in which a table can be related to another table: One-to-oneOne-to-many, and Many-to-many. The two first ones are the easiest to handle by adding the primary key of one table into the other table as a foreign key. However, the Many-to-many association is the trickiest relationship to represent and implement in a relational database. Relational systems usually don’t allow direct implementation of the many-to-many relationship between two tables. So to avoid duplicated data, we break the many-to-many relationship into two one-to-many relationships by using a third table, called a join table.

The following example shows an Employees table, which contains a record for each employee, and a project table, which includes each project. A join table, Employee_project, creates two one-to-many relationships—one between each of the two tables.

Each record in a join table Employee_project includes a match field that contains the value of the primary keys of the two tables Employee and Project as foreign keys. 

The Many-To-Many association in Sequelize

A many-to-many ( M: N) association is one of the three standard database relationships supported by Sequelize, and it is a combination of two basic relationships: belongsToMany association.

As we said in the section above, the many-to-many relationship cannot be implemented by adding a foreign key to one of the tables. So to represent this relationship between two tables with Sequelize, we use a third model called Junction Model and a corresponding table in the database. The Junction (or Join) table is automatically generated by Sequelize to represent the many-to-many association and will have two foreign keys.

To represent the relationship between the two models Employee and Project, we use the following two associations:

  const Employee = sequelize.define("Employee", { ... })
  const Project= sequelize.define("Project", { ... })

  Employee.belongsToMany(Project, { through: 'Employee_project' });
  Project.belongsToMany(Employee, { through: 'Employee_project' });

The purpose of the join table Employee_project is to store a record for each of the combinations of Employee and project tables by storing two columns: one for the primary key from the Employee table and one for the primary key from the Project table.

How to implement Many-To-Many association using Sequelize async/await in Node.js.

The rest of this article will show you how to implement the many-to-many relationship explained in the previous section using the association employees projects as an example in a Node.js and MySQL boilerplate API. We will use Sequelize ORM to connect the database, define the database tables, and interact with the Junction table.

The Node.js/Express startup API

We are starting with a boilerplate for the node.js server that uses express as a web server, and we name our project “manyToMany-example”. If you want to know more details about the start-server we are using in this article, go ahead and check this article: Complete Guide to Build a RESTful API with Node.js and Express.

server.js

 require("dotenv").config();
const express =require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
  
   
const app = express();
   
const PORT= process.env.APP_PORT;
   
app.use(bodyParser.json());
app.use(cors());
  
   
   
app.listen(PORT, ()=>{
    console.log(`server is listening  on ${PORT}`);
});
   
module.exports = app;

Inside the project directory manyToMany-example, create a .env file to save all the environment variables related to your API.

.env

 APP_PORT = 3000

package.json

 
 //package.json
   
{
  "name": "manyToMany-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
     
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "save": "^2.4.0"
  }
}

To create our database and establish a connection with it by initializing the Sequelize ORM, we need to follow these steps:

Step1: Create a MySQL Database

To create our database, we write a query in the db.js file, but first, we need to create this file:

In your project folder “manyToMany-example”, create a new JavaScript file and name it db.js. Then, install the mysql2 package inside the project directory and import it into db.js. Make sure it’s Mysql2 and not mysql.

 npm install --save mysql2

Now, open your db.js file and write the following SQL query to create the database named manyToMany_db“ if it doesn’t already exist.

db.js

 
 const config = require('./config.js');
const mysql = require('mysql2');
  
  
  
  
  
    // create db if it doesn't already exist
    const { host, port, user, password, database } = config.database;
     
    const pool =  mysql.createPool({ host, port, user, password });
       
   pool.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);


To save the configuration data and database connection options for the MySQL database, we create a separate file config.js  file like this:

config.js

 
 module.exports ={
   "database":{
        "host": "localhost",
        "port": 3306,
        "user": "root",
        "password": "enter your db password here",
        "database": "manyToMany_db"
   }
    
  
  
};

Notes:

Step2: Connect to MySQL database using Sequelize

As we said already, we will use Sequelize and mysql2 to connect our database, so the next step is to install and import the sequelize package.

 npm install --save sequelize

In the db.js file, we require the Sequelize class from the sequelize package; we use the capital letter because it’s a class.

Then, we create a new instance of this class to connect the database by passing specific parameters and options. To know more about these parameters, check HERE.

In order to use the sequelize instance in the other files of our project, we will attach it to the exported db object.

db.js

  const config = require('./config.js');
const mysql = require('mysql2');
 
const Sequelize = require('sequelize');
  
module.exports = db = {};
  
  
    // create db if it doesn't already exist
    const { host, port, user, password, database } = config.database;
      
   const pool =  mysql.createPool({ host, port, user, password });
  
     pool.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
  
    // connect to db
    const sequelize = new Sequelize(database, user, password, { dialect: 'mysql',
    pool: {
        max: config.pool.max,
        min: config.pool.min,
        acquire: config.pool.acquire,
        idle: config.pool.idle
      
      } }
      
    );
      
  
   db.sequelize = sequelize ;

config.js

  module.exports ={
   "database":{
        "host": "localhost",
        "port": 3306,
        "user": "root",
        "password": "enter your db password here",
        "database": "manyToMany_db"
   },
   "pool": {
    "max": 5,
    "min": 0,
    "acquire": 30000,
    "idle": 10000
  }
  
  
};

Note that, for more clean code in production mode, you can use the initialize() async function to write the queries to create the database connect it. If you want to see how to do that, you can check this article: Example How to use initialize() Function in Node.js/Express API.

Step3: Defining the Employee and Project Sequelize Models

The many-To-Many association is a relationship between two tables. That means we need to define and initialize two models to implement and perform this association. Sequelize will automatically create the corresponding tables in the MySQL database by calling the sequelize.sync(). 

In our database, we will have two tables, Employee and Project, so we will define two models Employee and Project.

So inside your project folder, please create a new folder and name it models. Then inside this folder, create Two new files (employee.js and project.js), one for each model.

We will use the define() method on the sequelize instance created already to define the two tables in the MySQL Database. If you want to know more about the define() method and how to define a model for MySQL table, please go HERE.

employee.js

 const { Sequelize, DataTypes } = require("sequelize");
  
const db = require('../db.js');
  
  
const  sequelize = db.sequelize;
  
const Employee = sequelize.define("Employee", {
  
 id: {
  
   type: DataTypes.INTEGER,
   autoIncrement: true,
   allowNull: false,
   primaryKey: true,
  
 },
  
 name: {
  
   type: DataTypes.STRING,
   allowNull: false,
  
 },
position: {
  
   type: DataTypes.STRING,
   allowNull: false,
  
 },
  
 email: {
  
   type: DataTypes.STRING,
   allowNull: false,
  
 },
wage: {
  
   type: DataTypes.INTEGER,
   allowNull: false,
  
 },
  
});
  
  
  
  
module.exports = Employee;

project.js

 const { Sequelize, DataTypes } = require("sequelize");
  
const db = require('../db.js');
  
  
const  sequelize = db.sequelize;
  
const Project = sequelize.define("Project", {
  
 id: {
  
   type: DataTypes.INTEGER,
   autoIncrement: true,
   allowNull: false,
   primaryKey: true,
  
 },
  
 name: {
  
   type: DataTypes.STRING,
   allowNull: false,
  
 }
 
 
  
});
  
  
  
module.exports = Project;

Step4: Sequelize Models Synchronisation

We use the sequelize.sync() to convert the two models to tables in the MySQL database. To do that, we need first to import our Employee and Project models and then initialize and attach them to the db object and then call the sequelize.sync(). 

db.js

  const config = require('./config.js');
const mysql = require('mysql2');
const Sequelize = require('sequelize');
  
module.exports = db = {};
  
  
    // create db if it doesn't already exist
    const { host, port, user, password, database } = config.database;
    const pool =  mysql.createPool({ host, port, user, password });
     pool.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
  
    // connect to db
    const sequelize = new Sequelize(database, user, password, { dialect: 'mysql',
    pool: {
        max: config.pool.max,
        min: config.pool.min,
        acquire: config.pool.acquire,
        idle: config.pool.idle
      
      } }
      
    );
      
    db.sequelize = sequelize ;
  
    // init the Employee and Project models and add them to the exported db object
    
   const Employee = require('./models/employee');
   
    const Project = require('./models/project');
 
    db.Employee = Employee;
   
    db.Project = Project;
  
    // sync all models with database
     sequelize.sync();



Now, all you have to do is start your server, and you will see in your terminal that the database and the tables have been created. For confirmation, you can use the Workbench interface.

We need to populate our tables Employees and Projects, to continue our demonstration. You can do that manually by using the Workbench interface or by creating routes in your API. To see how to do that, you can check here: How to add Routes to insert data into MySQL database-related tables in Node.js API?.

server.js

  require("dotenv").config();
const express =require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
  
const db = require('./db');
  
  
 const  sequelize = db.sequelize;
  
const app = express();
   
const PORT= process.env.APP_PORT;
   
app.use(bodyParser.json());
app.use(cors());
  
  
   
app.listen(PORT, ()=>{
    console.log(`server is listening  on ${PORT}`);
});
   
module.exports = app;

Defining the Many-To-Many association using Sequelize

To define the Many-To-Many relationship between the Project table and Employee table, we need to make sequelize know about this relation by representing these two associations:

 
  Employee.belongsToMany(Project, { through: 'Employee_project' });
  Project.belongsToMany(Employee, { through: 'Employee_project' });

So when Sequelize knows that the Project and Employee tables are related with the many-to-many association, it will automatically create a Junction table called Employee_project, which has two columns, employeeId, and projectId. The composite of these two keys will form a unique key for the join table. You can check that by using MySQL workbench.

In this tutorial, we will define ourselves a model Employee_project to be used as the through table so that no model will be created automatically. The advantage of this method is that we can define more columns on our junction table to track additional information. You can also force the join table to have a primary key just like other tables by defining the primary key in the junction model.

In our junction example model, we have two columns: EmployeeId and ProjectId. So inside the models’ folder, please create a new file and name it employee_project.js, then define the Employee_project junction model inside it.

employee_project.js

 const { Sequelize, DataTypes } = require("sequelize");
  
const db = require('../db.js');

 const Employee = db.Employee;
 const Project = db.Project;
  
  
const  sequelize = db.sequelize;
  
const Employee_project = sequelize.define("Employee_project", {
  
 EmployeeId: {
    type: DataTypes.INTEGER,
    references: {
      model: Employee, 
      key: 'id'
    }
  },
  ProjectId: {
    type: DataTypes.INTEGER,
    references: {
      model: Project, 
      key: 'id'
    }
  }
 
 
  
});
  
  
  
module.exports = Employee_project;

db.js

 const config = require('./config.js');
const mysql = require('mysql2');
const Sequelize = require('sequelize');
  
module.exports = db = {};
  
  
    // create db if it doesn't already exist
    const { host, port, user, password, database } = config.database;
    const pool =  mysql.createPool({ host, port, user, password });
     pool.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
  
    // connect to db
    const sequelize = new Sequelize(database, user, password, { dialect: 'mysql',
    pool: {
        max: config.pool.max,
        min: config.pool.min,
        acquire: config.pool.acquire,
        idle: config.pool.idle
      
      } }
      
    );
      
    db.sequelize = sequelize ;
 
   
  
  // init the Employee, Project and Employee_project models and add them to the exported db object
    
   const Employee = require('./models/employee');
   
    const Project = require('./models/project');

    const Employee_project = require('./models/employee_project');
 
    
   
 
    Employee.belongsToMany(Project, { through: Employee_project });
 
    Project.belongsToMany(Employee, { through: Employee_project });
 
    
    db.Employee = Employee;
   
    db.Project = Project;
    
    db.Employee_project = Employee_project;
    
   

    // sync all models with database
    
     sequelize.sync({force: true})
     
    

  

Note: We pass an object inside the sync() method and set the parameter force to true to validate any addition (like adding relationships between tables). This will drop the existing tables and then recreate them with the new information. Note that this is not recommended for production mode.

Creating Controllers for the Many-To-Many association using Sequelize async/await

In this section, we will write our controllers that use the many-to-many relationship inside a separated file called controller.js. So inside the project folder, please create a new file and name it controller.js. We will define our controllers as async functions. Then we will export these functions in order to call them in our router later.

For more details about async/await functions and promises, go ahead and check these articles: 

In the following, we will define seven functions in our controller.js file.

The first ones ( insertEmployee(), insertProject() ) insert data to the Employee and Project tables by using the create() method of the corresponding models.

  async function  insertEmployee(name, position, email, wage) {
 
  await Employee.create({name, position, email, wage});
 
 }


async function  insertProject(name) {
 
  await Project.create({name});
 
}

The third one is junctionCreate(). This function allows us to assign an employee to a project and record it in the Junction table Employee_project.

 async function junctionCreate(EmployeeId, ProjectId) {
  
  const employee_project = await Employee_project.create( { EmployeeId, ProjectId });
     
   return employee_project;
  
  
  }

The fourth function findAllEmployees() is to get all the employees from the Employee table with their projects using the junction table.

 async function findAllEmployees(){

const employees= await Employee.findAll({
  include: [
    {
      model: Project,
      
      attributes: ["name"],
      through: {
        attributes: ["EmployeeId", "ProjectId"],
      }

    },
  ],
});

return employees;



}
 
 

The findEmployeeProjects() takes the EmployeeId as a parameter and returns the employee with all his work projects.

 async function findEmployeeProjects(id){

  const employee= await Employee.findByPk(id, {
    include: [
      {
        model: Project,
        
        attributes: ["name"],
        through: {
          attributes: ["EmployeeId", "ProjectId"],
        }
  
      },
    ],
  });
  
  return employee;
  
  
  
  }

The findAllProjects() will get all the projects, including the employees assigned to them.

 async function findAllProjects(){

  const projects = await Project.findAll({
    include: [
      {
        model: Employee,
        
        attributes: ["name"],
        through: {
          attributes: ["EmployeeId", "ProjectId"],
        }
  
      },
    ],
  });
  
  return projects;
  
  
  
  }

findProjectEmployees(id) will get a specific project with id and all the employees assigned to this project.

 
async function findProjectEmployees(id){

    const project = await Project.findByPk(id, {
      include: [
        {
          model: Employee,
          
          attributes: ["name"],
          through: {
            attributes: ["EmployeeId", "ProjectId"],
          }
    
        },
      ],
    });
    
    return project;
    
    
    
    }

controller.js

 const db = require('./db');
  
const Employee = db.Employee;
const Project = db.Project;

const Employee_project = db.Employee_project;

 module.exports ={
 
  junctionCreate,
   insertEmployee,
   insertProject,
   findAllEmployees,
   findEmployeeProjects,
   findAllProjects,
   findProjectEmployees
 
 };
 


 async function  insertEmployee(name, position, email, wage) {
 
  await Employee.create({name, position, email, wage});
 
}


async function  insertProject(name) {
 
  await Project.create({name});
 
}







 
 async function junctionCreate(EmployeeId, ProjectId) {
  
  const employee_project = await Employee_project.create( { EmployeeId, ProjectId });
     
   return employee_project;
  
  
  }
  
  
  
  
 
   
  


async function findAllEmployees(){

const employees= await Employee.findAll({
  include: [
    {
      model: Project,
      
      attributes: ["name"],
      through: {
        attributes: ["EmployeeId", "ProjectId"],
      }

    },
  ],
});

return employees;



}
 
 


async function findEmployeeProjects(id){

  const employee= await Employee.findByPk(id, {
    include: [
      {
        model: Project,
        
        attributes: ["name"],
        through: {
          attributes: ["EmployeeId", "ProjectId"],
        }
  
      },
    ],
  });
  
  return employee;
  
  
  
  }





async function findAllProjects(){

  const projects = await Project.findAll({
    include: [
      {
        model: Employee,
        
        attributes: ["name"],
        through: {
          attributes: ["EmployeeId", "ProjectId"],
        }
  
      },
    ],
  });
  
  return projects;
  
  
  
  }
   





  async function findProjectEmployees(id){

    const project = await Project.findByPk(id, {
      include: [
        {
          model: Employee,
          
          attributes: ["name"],
          through: {
            attributes: ["EmployeeId", "ProjectId"],
          }
    
        },
      ],
    });
    
    return project;
    
    
    
    }






Adding API Routes for the Many-To-Many association Controllers using async functions

After exporting the controller functions, now we are going to use them in our routes. For that, we need to create a new file named apiRouter.js inside the project directory. This apiRouter will serve as the starting point for all your API routes.

Before adding routes to your apiRouter.js, first, you need to pull in the async functions from controller.js by adding this line of code to your apiRouter.js. To write our routes, we use the async functions.

  
 const  {junctionCreate, findAllEmployees, findEmployeeProjects, findAllProjects, findProjectEmployees, insertEmployee,
    insertProject }= require('./controller.js');

apiRouter.js

  
  //apiRouter.js
 
const express =require('express');
const apiRouter = express.Router();
const  {junctionCreate, findAllEmployees,findEmployeeProjects, findAllProjects,findProjectEmployees, insertEmployee,
    insertProject }= require('./controller.js');
 
 
 
 
    // Create an employee
 
apiRouter.post('/employee',  async (req, res, next)=>{
    try{
        const name = req.body.employee.name;
        const position = req.body.employee.position;
        const email = req.body.employee.email;
        const wage = req.body.employee.wage;
        console.log(name);
              if (!name || !position || !wage) {
                return res.sendStatus(400);
             }
  
        const employee =  await insertEmployee(name, position, email, wage).then(() => res.json({ message: 'Employee created.' }));
         
         
  
    } catch(e){
        console.log(e);
        res.sendStatus(400);
    }
 });








 // Create a project
 
apiRouter.post('/project',  async (req, res, next)=>{
    try{
        const name = req.body.project.name;
        
        console.log(name);
              if (!name) {
                return res.sendStatus(400);
             }
  
        const company =  await insertProject(name).then(() => res.json({ message: 'Project created.' }));
         
         
  
    } catch(e){
        console.log(e);
        res.sendStatus(400);
    }
 });

 







  // Create a record in the junction table Employee_project.
 
apiRouter.post('/employee-project',  async (req, res, next)=>{
    try{
        const employeeId = req.body.employeeProject.EmployeeId;
        const projectId = req.body.employeeProject.ProjectId;
        console.log(employeeId);
        console.log(projectId);
        
              if (!employeeId || !projectId) {
                return res.sendStatus(400);
             }
  
        const employeeProject =  await junctionCreate(employeeId, projectId).then(() => res.json({ message: 'Employee project created.' }));
         
         
  
    } catch(e){
        console.log(e);
        res.sendStatus(400);
    }
 });
 
   
 
 
 
 
   
  
 
   // Get all employees and the projects they are working on using the junction table.
  
 apiRouter.get('/employee-project', async (req, res, next)=>{
    try {
        const employees = await findAllEmployees();
        res.status(200).json({employees: employees});
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
 });
 



// Get an employee projects

 apiRouter.param('employeeId', async (req, res, next, employeeId)=> {
    try{
        const employee = await findEmployeeProjects(employeeId);
        console.log(employee);
        req.employee = employee;
        next(); // go to apiRouter.get('/employee/:employeeId')
    } catch(e) {
        console.log(e);
        res.sendStatus(404);
    }
 });
  
  
  
  
 apiRouter.get('/employee/:employeeId',  (req, res, next)=>{
    res.status(200).json({employee: req.employee});
 });












// Get all projects and the employees  working on them using the junction table.
  
apiRouter.get('/project-employee', async (req, res, next)=>{
    try {
        const projects = await findAllProjects();
        res.status(200).json({projects: projects});
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
 });



 // Get a project employees
 
 apiRouter.param('projectId', async (req, res, next, projectId)=> {
    try{
        const project = await findProjectEmployees(projectId);
        req.project = project;
        next(); // go to apiRouter.get('/project/:projectId')
    } catch(e) {
        console.log(e);
        res.sendStatus(404);
    }
 });
  
  
 apiRouter.get('/project/:projectId',  (req, res, next)=>{
    res.status(200).json({project: req.project});
 });




 
 
module.exports = apiRouter;

Testing our API routes with Postman

Before you start testing the API with Postman, you need first to change the sequelize.sync({force: true}) to sequelize.sync() in the db.js file, then start your node.js app and insert the following data into the database tables. If you want to see how to add routes to your API to do that, you can check here: How to add Routes to insert data into MySQL database-related tables in Node.js API?.

Employees table:

idnamepositionemailwage
1employee1manager[email protected]8000
2employee2engineer[email protected]6000
3employee3designer[email protected]5000
4employee4architect[email protected]6000

Projects table:

idname
1project1
2project2
3project3

Employee_projects table:

EmployeeIdProjectId
11
12
32
41
43
23

Note: if you try to insert an employeeId or a projectId which does not exist into the Employee_projects table, you will get an error message:

1- Create an employee.

To create and insert an employee to Employees table, use the following setting in your Postman:

  • Path: apiRouter/employee
  • Method: POST
  • URL: http://localhost:3000/apiRouter/employee
  • Change the body type to “raw”
  • Change the format to “JSON”
  • The json object: {“employee” : {“name”: “employee1″,”position”: “manager”,”email”: “[email protected]”,”wage” : 8000}}

2- Create a project.

To create and insert a project to Projects table, use the following setting in your Postman:

  • Path: apiRouter/project
  • Method: POST
  • URL: http://localhost:3000/apiRouter/project
  • Change the body type to “raw”
  • Change the format to “JSON”
  • The json object: {“project” : {“name”: “project1}}

3- Assign an employee to a project.

Assigning an employee with an EmployeeId: 1 to a project with ProjectId: 2 means inserting the combination (1,2) to the Employee_projects table. To do that, you need to use the following setting in your Postman:

  • Path: apiRouter/employee-project
  • Method: POST
  • URL: http://localhost:3000/apiRouter/employee-project
  • Change the body type to “raw”
  • Change the format to “JSON”
  • The json object: {“employeeProject” : {“EmployeeId”:1 ,”ProjectId”: 2}}

4- Get all employees and the projects they are working on

To Get all employees and the projects they are working on using the junction tablEmployee_projects table, use the following setting in your Postman:

  • Path: apiRouter/employee-project
  • Method: GET
  • URL: http://localhost:3000/apiRouter/employee-project
  • Change the body type to “raw”
  • Change the format to “JSON”

4- Get an employee projects

To Get the projects of an employee with EmployeeId: 2, use the following setting in your Postman:

  • Path: apiRouter/employee/:employeeId
  • Method: GET
  • URL: http://localhost:3000/apiRouter/employee/2
  • Change the body type to “raw”
  • Change the format to “JSON”

5- Get all projects and the employees working on them

To get all projects and the employees working on them using the junction table, use the following setting in your Postman:

  • Path: apiRouter/project-employee
  • Method: GET
  • URL: http://localhost:3000/apiRouter/project-employee
  • Change the body type to “raw”
  • Change the format to “JSON”

6- Get a project employees

To Get all employees working on a project with projectId: 3, use the following setting in your Postman:

  • Path: apiRouter/project/:projectId
  • Method: GET
  • URL: http://localhost:3000/apiRouter/project/3
  • Change the body type to “raw”
  • Change the format to “JSON”

Conclusion

This article showed you how to define and use many-to-many association in a MySQL database using Sequelize async/await. I hope this was helpful for you.

If you want to read our articles on how to define and use one-to-many and one-to-one associations, please go here:

To see the rest of the CRUD API and how to write the controller using Sequelize async/await, read this article: How to use Sequelize async/await to interact with MySQL database in Node.js.

To implement your API using the initialize() function to connect MySQL server, connect a database with Sequelize ORM, and initialize the models, go here: Example How to use initialize() Function in Node.js/Express API.

You might also like:

ONE-TO-MANY Association in MYSQL Database using Sequelize async/await with Node.js.

ONE-TO-ONE Association in MYSQL Database using Sequelize async/await with Node.js.

Example How to use initialize() Function in Node.js/Express API .

How to use Sequelize async/await to interact with MySQL database in Node.js.

How to add Routes to insert data into MySQL database-related tables in Node.js API?

How to interact with MySQL database using async/await promises in node.js ?

How to Build a Complete API for User Login and Authentication using MySQL and Node.js.

Why is Connection Pooling better than Single Connection?.

How to create MySQL database using node.js.

How to store Session in MySQL Database using express-mysql-session.

Complete Guide to Build a RESTful API with Node.js and Express.

Translate »