In modern web development, integrating a database is essential for storing and managing data efficiently. Node.js, being an asynchronous event-driven JavaScript runtime, provides several options for database integration. This tutorial will cover the basics of integrating databases with Node.js, focusing on popular choices like MongoDB and MySQL.
Before diving into database integration, ensure you have the following:
First, create a new directory for your project and initialize it with npm.
mkdir nodejs-database-integration
cd nodejs-database-integration
npm init -y
Install the necessary dependencies:
npm install express mongoose mysql2 sequelize
MongoDB is a popular NoSQL database that stores data in JSON-like documents. We'll use Mongoose, an ODM (Object Data Modeling) library for MongoDB and Node.js.
Create a file named db.js to handle the database connection:
// db.js
const mongoose = require('mongoose');
async function connect() {
try {
await mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('Connected to MongoDB');
} catch (error) {
console.error('Failed to connect to MongoDB:', error);
}
}
module.exports = { connect };
Create a file named userModel.js to define a user model:
// userModel.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number,
});
module.exports = mongoose.model('User', userSchema);
Create an app.js file to set up your Express server and use the Mongoose model:
// app.js
const express = require('express');
const { connect } = require('./db');
const User = require('./userModel');
const app = express();
app.use(express.json());
connect();
app.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
});
app.get('/users', async (req, res) => {
const users = await User.find({});
res.send(users);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start your MongoDB server and run your Node.js application:
mongod
node app.js
Test the API using tools like Postman or curl:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com", "age": 30}'
curl http://localhost:3000/users
MySQL is a popular relational database management system. We'll use Sequelize, an ORM (Object-Relational Mapping) library for Node.js.
Create a file named db-mysql.js to handle the database connection:
// db-mysql.js
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('mydatabase', 'root', 'password', {
host: 'localhost',
dialect: 'mysql'
});
async function connect() {
try {
await sequelize.authenticate();
console.log('Connected to MySQL');
} catch (error) {
console.error('Failed to connect to MySQL:', error);
}
}
module.exports = { sequelize, connect };
Create a file named userModel-mysql.js to define a user model:
// userModel-mysql.js
const { DataTypes } = require('sequelize');
const { sequelize } = require('./db-mysql');
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
age: {
type: DataTypes.INTEGER,
allowNull: false
}
});
module.exports = User;
Modify your app.js file to use Sequelize:
// app.js
const express = require('express');
const { connect } = require('./db-mysql');
const User = require('./userModel-mysql');
const app = express();
app.use(express.json());
connect();
app.post('/users', async (req, res) => {
const user = await User.create(req.body);
res.status(201).send(user);
});
app.get('/users', async (req, res) => {
const users = await User.findAll();
res.send(users);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Ensure your MySQL server is running and create the database (mydatabase) manually. Then run your Node.js application:
mysql -u root -p
CREATE DATABASE mydatabase;
exit
node app.js
Test the API using tools like Postman or curl:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com", "age": 30}'
curl http://localhost:3000/users
Integrating databases with Node.js is crucial for building robust applications. Whether you choose MongoDB or MySQL, using libraries like Mongoose and Sequelize can simplify the process significantly. By following best practices and understanding the basics of each database system, you can effectively manage data persistence in your Node.js projects.