Introduction
Databases play a crucial role in web applications by storing and retrieving data efficiently. Node.js supports both SQL (e.g., MySQL, PostgreSQL) and NoSQL (e.g., MongoDB) databases. This chapter covers connecting Node.js applications to databases, performing CRUD operations, and using an ORM (Object-Relational Mapping) library.
1. Choosing a Database
There are two main types of databases:
SQL (Relational Databases)
- MySQL
- PostgreSQL
- SQLite
NoSQL (Non-Relational Databases)
- MongoDB
- Redis
- Firebase
Choosing between SQL and NoSQL depends on your project’s requirements. SQL databases are structured, while NoSQL databases are flexible and scalable.
2. Connecting to a SQL Database (MySQL)
Install the MySQL package:
npm install mysql2
Example: Connecting to MySQL
const mysql = require("mysql2");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "testdb"
});
connection.connect(err => {
if (err) throw err;
console.log("Connected to MySQL database");
});
Executing a Query
connection.query("SELECT * FROM users", (err, results) => {
if (err) throw err;
console.log(results);
});
3. Connecting to a NoSQL Database (MongoDB)
MongoDB is a document-based NoSQL database. Install the MongoDB package:
npm install mongoose
Example: Connecting to MongoDB
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydatabase", {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log("Connected to MongoDB"))
.catch(err => console.log(err));
4. Performing CRUD Operations
SQL CRUD Operations
Create (INSERT)
const sql = "INSERT INTO users (name, age) VALUES (?, ?)";
connection.query(sql, ["Alice", 25], (err, result) => {
if (err) throw err;
console.log("User added");
});
Read (SELECT)
connection.query("SELECT * FROM users", (err, results) => {
if (err) throw err;
console.log(results);
});
Update (UPDATE)
const sql = "UPDATE users SET age = ? WHERE name = ?";
connection.query(sql, [30, "Alice"], (err, result) => {
if (err) throw err;
console.log("User updated");
});
Delete (DELETE)
const sql = "DELETE FROM users WHERE name = ?";
connection.query(sql, ["Alice"], (err, result) => {
if (err) throw err;
console.log("User deleted");
});
NoSQL CRUD Operations with MongoDB
Define a Schema and Model
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model("User", userSchema);
Create a Document
const newUser = new User({ name: "Alice", age: 25 });
newUser.save().then(() => console.log("User added"));
Read Data
User.find().then(users => console.log(users));
Update Data
User.updateOne({ name: "Alice" }, { age: 30 }).then(() => console.log("User updated"));
Delete Data
User.deleteOne({ name: "Alice" }).then(() => console.log("User deleted"));
5. Using an ORM (Sequelize for SQL, Mongoose for NoSQL)
Using an ORM simplifies database interactions by abstracting SQL queries.
Sequelize (SQL ORM)
npm install sequelize mysql2
Defining a Model
const { Sequelize, DataTypes } = require("sequelize");
const sequelize = new Sequelize("testdb", "root", "password", { dialect: "mysql" });
const User = sequelize.define("User", {
name: { type: DataTypes.STRING, allowNull: false },
age: { type: DataTypes.INTEGER }
});
sequelize.sync().then(() => console.log("Database synced"));
Mongoose (NoSQL ORM)
npm install mongoose
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model("User", userSchema);
🏆 Exercises
- 1. Connect to a MySQL database and create a users table.
- 2. Insert a user into the MySQL database and retrieve the data.
- 3. Connect to a MongoDB database and insert a document.
- 4. Update and delete a user from both MySQL and MongoDB.
- 5. Use an ORM like Sequelize or Mongoose to manage database interactions.
Conclusion
Node.js supports both SQL and NoSQL databases, and you can choose based on your project needs. We covered how to connect, perform CRUD operations, and use ORMs for database management. The next chapter will focus on authentication and security in Node.js applications.