Connecting Node.
js with a database involves the following steps:
🧩 Common Databases Used with Node.js
Database Type Examples
Relational (SQL) MySQL, PostgreSQL, SQLite, Microsoft SQL Server
NoSQL MongoDB, Redis, Cassandra
🔗 Steps to Connect Node.js with a Database
1. Install Required Packages
Use npm to install the driver/library for your database.
Database Library Install Command
MongoDB mongoose or mongodb npm install mongoose
MySQL mysql2 npm install mysql2
PostgreSQL pg npm install pg
SQLite sqlite3 npm install sqlite3
2. Establish Connection (Examples)
👉 MongoDB using Mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb')
.then(() => console.log('MongoDB Connected'))
.catch(err => console.error('Connection error', err));
👉 MySQL using mysql2
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'yourpassword',
database: 'mydb'
});
connection.connect(err => {
if (err) throw err;
console.log('MySQL Connected!');
});
👉 PostgreSQL using pg
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'postgres',
password: 'yourpassword',
database: 'mydb'
});
client.connect()
.then(() => console.log('PostgreSQL Connected'))
.catch(err => console.error('Connection error', err.stack));
3. Perform CRUD Operations
// For MongoDB
const User = mongoose.model('User', { name: String });
const user = new User({ name: 'Alice' });
user.save().then(() => console.log('User saved'));
// For MySQL
connection.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
});
📌 Best Practices
Use Environment Variables for credentials (with .env + dotenv package).
Use Connection Pooling for better performance.
Use ORM/ODM tools (e.g., Sequelize for SQL, Mongoose for MongoDB).
Use Async/Await or Promises for clean code.