Sequelize helps you talk to databases easily using JavaScript. It turns database tables into objects you can work with in your code.
Sequelize ORM setup in 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.
const sequelize = new Sequelize('mydb', 'user', 'pass', { host: 'localhost', dialect: 'postgres' });
const sequelize = new Sequelize('sqlite::memory:');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.
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();
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.
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.