In the previous part of our Node.js series, we introduced Express.js, a powerful web application framework that simplifies server-side development. Now, let's take a significant step forward by integrating a database into our application. Databases are crucial for storing and retrieving persistent data. In this part, we'll explore how to connect to both SQL and NoSQL databases using Node.js.
please subscribe to my YouTube channel to support my channel and get more web development tutorials.
Overview of Databases
There are two primary types of databases commonly used with Node.js:
- SQL Databases: These include relational databases like MySQL, PostgreSQL, and SQLite. They use structured query language (SQL) for defining and manipulating data.
- NoSQL Databases: These include document-oriented databases like MongoDB. They provide flexible schemas and scale horizontally.
We'll cover examples of connecting to both a SQL and a NoSQL database.
Connecting to a SQL Database (MySQL)
Step 1: Install MySQL and Node.js Packages
First, ensure you have MySQL installed on your system. You can download it from the official MySQL website.
Next, install the mysql2
package in your Node.js project:
npm install mysql2
Step 2: Create a MySQL Database and Table
Log in to your MySQL server and create a new database and table for demonstration purposes:
CREATE DATABASE nodejs_demo;
USE nodejs_demo;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
Step 3: Connect to MySQL from Node.js
Create a file named database.js
and add the following code to connect to your MySQL database:
database.js
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'nodejs_demo'
});
connection.connect(err => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
console.log('Connected to MySQL as ID', connection.threadId);
});
module.exports = connection;
Step 4: Interacting with the Database
Now, let’s add some code to interact with the database. Create a file named app.js
and use the following code to insert and retrieve data:
app.js
const express = require('express');
const connection = require('./database');
const app = express();
app.use(express.json());
// Insert a new user
app.post('/users', (req, res) => {
const { name, email } = req.body;
connection.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.status(201).send({ id: results.insertId, name, email });
});
});
// Get all users
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.send(results);
});
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Connecting to a NoSQL Database (MongoDB)
Step 1: Install MongoDB and Node.js Packages
Ensure MongoDB is installed on your system. You can download it from the official MongoDB website.
Next, install the mongoose
package in your Node.js project:
npm install mongoose
Step 2: Connect to MongoDB from Node.js
Create a file named database.js
and add the following code to connect to your MongoDB database:
database.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/nodejs_demo', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
module.exports = mongoose;
Step 3: Define a Mongoose Schema and Model
Create a file named userModel.js
and define a schema and model for users:
userModel.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true }
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Step 4: Interacting with the Database
Use the following code in app.js
to insert and retrieve data from MongoDB:
app.js
const express = require('express');
const mongoose = require('./database');
const User = require('./userModel');
const app = express();
app.use(express.json());
// Insert a new user
app.post('/users', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
} catch (err) {
res.status(400).send(err);
}
});
// Get all users
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.send(users);
} catch (err) {
res.status(500).send(err);
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Conclusion
Integrating databases with your Node.js applications allows you to manage and persist data efficiently. Whether using SQL databases like MySQL or NoSQL databases like MongoDB, Node.js provides powerful tools and libraries to facilitate database operations. In the next part of our series, we’ll explore authentication and authorization, essential for securing your applications.
Stay tuned for more advanced Node.js development techniques! Next->
Feel free to leave your comments or questions below. If you found this guide helpful, please share it with your peers and follow me for more web development tutorials. Happy coding!
Follow and Subscribe:
- Website: Dipak Ahirav
- Email: dipaksahirav@gmail.com
- Instagram: devdivewithdipak
- YouTube: devDive with Dipak
- LinkedIn: Dipak Ahirav
Top comments (3)
Very informative, you're a great help
Thanks @samir419 , kindly subscribe to my YouTube channel to support my channel and get more web development tutorials.
Next part -> Day-8