0
0
Expressframework~5 mins

Sequelize ORM setup in Express

Choose your learning style9 modes available
Introduction

Sequelize helps you talk to databases easily using JavaScript. It turns database tables into objects you can work with in your code.

You want to save and get data from a database in your Express app.
You prefer writing JavaScript instead of SQL queries.
You need to manage database tables and relationships in a simple way.
You want to switch databases later without changing much code.
You want to organize your database code cleanly in your project.
Syntax
Express
const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql' // or 'postgres', 'sqlite', 'mssql'
});

Replace 'database', 'username', and 'password' with your actual database info.

The 'dialect' tells Sequelize which database type you use.

Examples
Connects to a PostgreSQL database named 'mydb' on your local machine.
Express
const sequelize = new Sequelize('mydb', 'user', 'pass', {
  host: 'localhost',
  dialect: 'postgres'
});
Creates a temporary SQLite database in memory, useful for testing.
Express
const sequelize = new Sequelize('sqlite::memory:');
Sample Program

This Express app sets up Sequelize to connect to a MySQL database named 'testdb'. It defines a User model with username and email fields. It tests the database connection, syncs the model (creates the table), and starts the server.

Express
const express = require('express');
const { Sequelize, DataTypes } = require('sequelize');

const app = express();
const port = 3000;

// Setup Sequelize connection
const sequelize = new Sequelize('testdb', 'root', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});

// Define a simple model
const User = sequelize.define('User', {
  username: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false
  }
});

// Test connection and sync model
async function start() {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
    await sequelize.sync({ force: true });
    console.log('All models were synchronized successfully.');

    app.listen(port, () => {
      console.log(`Server running on http://localhost:${port}`);
    });
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
}

start();
OutputSuccess
Important Notes

Make sure your database server is running before starting the app.

Use environment variables to keep your database credentials safe instead of hardcoding.

Calling sequelize.sync({ force: true }) deletes existing tables and recreates them, so use carefully.

Summary

Sequelize lets you connect your Express app to databases using JavaScript objects.

Setup involves creating a Sequelize instance with your database info and defining models.

Always test the connection and sync models before running your app.