We will learn how to use Sequelize, a powerful and flexible ORM (Object-Relational Mapping) tool for Node.js, to connect to SQL databases like MySQL and PostgreSQL in this section. Sequelize hides the difficulty of working with SQL databases so that you can use JavaScript objects instead of writing raw SQL queries to deal with your database. We will talk about how to link to a database, set up schemas and models, and do CRUD tasks.
To begin, make a new Node.js app and add the resources you need:
mkdir sequelize-app
cd sequelize-app
npm init -y
Next, install both Sequelize and the MySQL or PostgreSQL database tools that you need.
npm install sequelize mysql2
npm install sequelize pg pg-hstore
Getting connected to your SQL database is the next step after setting up your project. Create a config/database.js file:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'localhost',
dialect: 'mysql', // or 'postgres' for PostgreSQL
});
sequelize.authenticate()
.then(() => console.log('Database connected...'))
.catch(err => console.log('Error: ' + err));
module.exports = sequelize;
Now that you've connected to the database, you can use Sequelize models to create your data layout. Create a models/user.js file:
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const User = sequelize.define('User', {
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
}
}, {
timestamps: true
});
module.exports = User;
firstName, lastName, and email.Once the models are set, you can do CRUD tasks on the database. Create a routes/userRoutes.js file:
const express = require('express');
const User = require('../models/user');
const router = express.Router();
// Create a new user
router.post('/users', async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Get all users
router.get('/users', async (req, res) => {
try {
const users = await User.findAll();
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get a user by ID
router.get('/users/:id', async (req, res) => {
try {
const user = await User.findByPk(req.params.id);
if (user) {
res.json(user);
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Update a user by ID
router.put('/users/:id', async (req, res) => {
try {
const user = await User.update(req.body, { where: { id: req.params.id }, returning: true });
res.json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Delete a user by ID
router.delete('/users/:id', async (req, res) => {
try {
const result = await User.destroy({ where: { id: req.params.id } });
if (result) {
res.json({ message: 'User deleted' });
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
Make sure that Sequelize syncs your models with the database before you run the server. Update app.js to include syncing:
const express = require('express');
const sequelize = require('./config/database');
const userRoutes = require('./routes/userRoutes');
const app = express();
app.use(express.json());
app.use('/api', userRoutes);
sequelize.sync({ alter: true })
.then(() => {
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
})
.catch(err => console.log('Error: ' + err));
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved