codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

30 / 63 topics
30Database Integration31MongoDB with Node.js32Mongoose ORM33SQL Databases with Node.js34Sequelize ORM
Tutorials/Node.js/Database Integration
🟢Node.js

Database Integration

Updated 2026-04-20
3 min read

Database Integration

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.

Prerequisites

Before diving into database integration, ensure you have the following:

  • Basic knowledge of Node.js.
  • Node.js installed on your machine.
  • A code editor (e.g., VSCode).
  • Understanding of SQL and NoSQL concepts.

Setting Up a Node.js Project

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 Integration

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.

Step 1: Connect to MongoDB

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 };

Step 2: Define a Mongoose Model

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);

Step 3: Use the Model in Your Application

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');
});

Step 4: Test the Application

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 Integration

MySQL is a popular relational database management system. We'll use Sequelize, an ORM (Object-Relational Mapping) library for Node.js.

Step 1: Connect to MySQL

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 };

Step 2: Define a Sequelize Model

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;

Step 3: Use the Model in Your Application

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');
});

Step 4: Test the Application

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

Best Practices

  1. Error Handling: Always handle errors gracefully to avoid crashing your application.
  2. Environment Variables: Use environment variables for sensitive information like database credentials.
  3. Connection Pooling: Utilize connection pooling to manage database connections efficiently.
  4. Validation: Validate data before saving it to the database to prevent invalid entries.
  5. Testing: Write unit tests for your database interactions to ensure reliability.

Conclusion

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.


PreviousBuilding a Chat ApplicationNext MongoDB with Node.js

Recommended Gear

Building a Chat ApplicationMongoDB with Node.js